ASP.NET 5 Dependency Injection with Autofac

ASP.NET 5 Dependency Injection with Autofac

Earlier I wrote a blog post on ASP.NET MVC 6 Dependency Injection, which showed how to use dependency injection in ASP.NET 5 and ASP.NET MVC 6 web applications using the built-in dependency injection container. In this ASP.NET 5 Tutorial I will show how to use that same example using a more feature-rich dependency injection container called Autofac. If you are unfamiliar with dependency injection in ASP.NET 5 and ASP.NET MVC 6, please read the other tutotial first as well as the tutorial ASP.NET MVC 6 view injection.

Autofac IoC Container and Project.json

To use Autofac as your dependency injection container in ASP.NET 5 and ASP.NET MVC 6 you will need to reference a couple of dependencies in Project.json.

"Autofac"
"Autofac.Framework.DependencyInjection"

Startup Class and ConfigureServices Method

In the ConfigureServices Method of the Startup Class you will need to create the Autofac Container, populate it, buid it, and then return it as the new IServiceProvider ( dependency injection container ) used by your ASP.NET 5 Application. Here is example code for the Startup Class registering the TestService Class mentioned in the earlier post: ASP.NET MVC 6 Dependency Injection.

public IServiceProvider
  ConfigureServices(IServiceCollection services) {
    services.AddMvc();

    var builder = new ContainerBuilder();
    builder.RegisterType<Testservice>()
        .As<ITestService>()
        .InstancePerDependency();
    builder.Populate(services);

    var container = builder.Build();

    return container.Resolve<IServiceProvider>();
}

First, I create the ContainerBuilder in Autofac. I register my TestService as an ITestService. I add the existing dependencies to the Autofac Container via builder.Populate(services). Finally, I build the container and then return it as the new IServiceProvider.

Per the previous tutorial, we can now inject TestService in an ASP.NET MVC 6 Controller.

public class TestController : Controller {
    private readonly ITestService _testService;

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

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

Autofac is a very rich dependency injection framework. I recommend you read the documentation and learn about various proven practices on how to register dependencies using modules and extensions.