ASP.NET MVC 6 Dependency Injection

ASP.NET MVC 6 Dependency Injection

ASP.NET MVC 6 comes with a basic dependency injection container that will allow you to implement constructor and property dependency injection into your controller classes. This may be enough for smaller ASP.NET MVC 6 applications while other applications can continue to use Autofac, Ninject, StructureMap, Unity, etc.

ASP.NET MVC 6 Dependency Injection

The key to dependency injection in ASP.NET MVC 6 is to register your services in the Startup File's ConfigureServices Method. Here is an example of registering a TestService:

public void ConfigureServices(IServiceCollection services) {
    ...
    services.AddTransient<ITestService, TestService>();
}

One can declare services as one of 4 types:

  • Instance: A specific instance is given all the time. You are responsible for its initial creation
  • Transient: A new instance is created every time
  • Singleton: A single instance is created and it acts like a singleton
  • Scoped: A single instance is created inside the current scope. It is equivalent to Singleton in the current scope

Once you have registered the new service with the dependency injection container in ASP.NET MVC 6 you can either inject the service into the constructor of a controller class or the property of a controller class.

In this example the service is injected into the constructor of the controller class:

public class TestController : Controller {
    private readonly ITestService _testService;

    public TestController(ITestService testService) {
        _testService = testService;
    }

    public IActionResult Index() {
        _testService.DoIt();
        ...
    }
}

In this example the service is injected into the property of the controller class. Notice the [FromServices] Attribute on the property.

public class TestController : Controller {
    [FromServices]
    public ITestService TestService { get; set; }

    public IActionResult Index() {
        TestService.DoIt();
        ...
    }
}

You can mix and match both constructor and property injection on your controller classes.

Conclusion

There is a lot more to dependency injection, but this tutorial gives you a quick introduction to the basics of registering services and injecting those services into your ASP.NET MVC 6 Controllers.