0

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(); } } 
2
  • How you write the implement of IApiService? Did you add dependency injection configuration in startup.cs? Commented Apr 12, 2022 at 6:18
  • no I didn't. How should I add to it? Commented Apr 12, 2022 at 6:25

1 Answer 1

1

For asp.net framework:

enter image description here

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.

enter image description here

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>(); 
Sign up to request clarification or add additional context in comments.

4 Comments

Bruh I have another problem. I couldn't find startup.cs
You created a .net 6 project? Is there a Program.cs file?
No it's .net Framework
I searched for document and found that asp.net framework is different. I've updated my answer,

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.