Asp.net MVC boilerplate dependency injection not working
Asked Answered
F

1

6

I'm playing with the Asp.Net MVC 6 boilerplate project. I'm trying to configure the dependency injection for one of my services. It seems like the built in IoC container is ignoring my binding.

Startup.cs

public void ConfigureServices(IServiceCollection services){
    /*boilerplate's 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);
}

Exception:

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

Could you please tell me what is am I doing wrong?

Fireback answered 25/7, 2016 at 17:34 Comment(0)
I
7

That exception is because the framework cannot bind action arguments to interfaces.

You are trying to do the injection on the Action when the framework by default uses constructor injection.

Reference: Dependency Injection and Controllers

Constructor Injection

ASP.NET Core’s built-in support for constructor-based dependency injection extends to MVC controllers. By simply adding a service type to your controller as a constructor parameter, ASP.NET Core will attempt to resolve that 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 should request their dependencies explicitly via their constructors. In some instances, individual controller actions may require a service, and it may not make sense to request at the controller level. In this case, you can also choose to inject a service as a parameter on the action method.

Action Injection with FromServices

Sometimes you don’t need a service for more than one action within your controller. In this case, it may make sense to inject the service as a parameter to the action method. This is done by marking the parameter with the attribute [FromServices] as shown here:

public IActionResult Index([FromServices] IDummy dummy) {
    var test = dummy.name;
    return this.View(HomeControllerAction.Index);
}
Isaac answered 25/7, 2016 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.