Asp.net MVC Injection Injection

I play with the Asp.Net MVC 6 project. I am trying to configure dependency injection for one of my services. It seems that the inline IoC container is ignoring my binding.

Startup.cs

public void ConfigureServices(IServiceCollection services){ /*boilerplate default bindings*/ services.AddTransient<IDummy, Dummy>(p => new Dummy() { name = "from injection" }); } 

HomeController.cs

 public IActionResult Index(IDummy dummy){ var test = dummy.name; return this.View(HomeControllerAction.Index); } 

An exception:

ArgumentException: Type "Presentation.WebUI.Controllers.IDummy" does not have a default constructor

Could you tell me what I am doing wrong?

+6
source share
1 answer

This exception is that the structure cannot bind action arguments to interfaces.

You are trying to inject into Action when the default environment uses constructor injection.

Link: Injections and dependency controllers

Constructor Injection

Native ASP.NET Core support for constructor-based dependencies injection extends to MVCs. By simply adding a service type for your controller as a constructor parameter, ASP.NET Core will try to enable this type using its built-in service container.

 public class HomeController : Controller { IDummy dummy; public HomeController(IDummy dummy) { this.dummy = dummy } public IActionResult Index(){ var test = dummy.name; return this.View(HomeControllerAction.Index); } } 

ASP.NET Core MVC controllers must request their dependencies explicitly through their constructors. In some cases, individual controller actions may require maintenance, and it may not make sense to request at the controller level. In this case, you can also choose to enter the service as a parameter in the action method.

Enabling Injection Using FromServices Services

Sometimes you do not need a service for more than one action inside your controller. In this case, it may be appropriate to introduce the service as a parameter of the action method. This is done by marking with the [FromServices] attribute, as shown below:

 public IActionResult Index([FromServices] IDummy dummy) { var test = dummy.name; return this.View(HomeControllerAction.Index); } 
+7
source

All Articles