hello guys I have problem with this error. my project is simple I have an Interface called "IApiService" and I have a class called Api that is relative with my IApiService Interface. So in "Api" I have a method that post an api and I think this error doesn't relative with my error. I think error is in my Controller. So I will put my controller code so you guys could help me with! Here it is:
public class HomeController : Controller
{
IApiService _apiService;
public HomeController(IApiService apiService)
{
_apiService = apiService;
}
// GET: Home
public async Task<ActionResult> Index(CheckOutViewModel model)
{
var result = await _apiService.CheckOut(model);
return View();
}
}
CodePudding user response:
For asp.net framework:
The difference is that you should have your controller like this, no need to inject dependency:
public class HomeController : Controller
{
IApiService _apiService;
public HomeController() : this(new ApiService())
{
}
public HomeController(IApiService apiService)
{
_apiService = apiService;
}
public string getString(string name) {
string a = _apiService.CheckOut(name);
return a;
}
}
==============================================
Please allow me to show a sample here, asp.net core.
My Controller:
public class HomeController : Controller
{
private readonly IApiService _apiService;
public HomeController( IApiService iapiService)
{
_apiService = iapiService;
}
public string getString(string name) {
string a = _apiService.CheckOut(name);
return a;
}
}
My interface:
namespace WebMvcApp.Services
{
public interface IApiService
{
public string CheckOut(string str);
}
}
My implement of the interface:
namespace WebMvcApp.Services
{
public class ApiService: IApiService
{
public string CheckOut(string str)
{
return "hello : " str;
}
}
}
I inject the dependency in startup.cs -> ConfigureServices method:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped<IApiService, ApiService>();
}
or in .net 6 in Program.cs file:
builder.Services.AddControllersWithViews();
builder.Services.AddScoped<IApiService, ApiService>();