Dependency injection with AutoFac in ASP.NET 5

Posted by Anuraj on Saturday, October 31, 2015

aspnet5 Dependency injection codeproject autofac

ASP.NET5 comes with inbuilt dependency injection framework. This post is about using Autofac DI framework instead the in built DI framework. You can find more details about ASP.NET5 DI Framework in ASP.NET5 DependencyInjection respository. And you can find more details about Autofac in Autofac documentation

First you need to refererence the Autofac related assemblies in the project.json file

"dependencies": {
  "Autofac": "4.0.0-beta8",
  "Autofac.Framework.DependencyInjection": "4.0.0-beta8",
  "Microsoft.AspNet.IISPlatformHandler": "1.0.0-beta8",
  "Microsoft.AspNet.Mvc": "6.0.0-beta8",
  "Microsoft.AspNet.Server.Kestrel": "1.0.0-beta8"
}

I am using the autofac getting started example interface and implementation.

public interface IOutput
{
    void Write(string content);
}

And here is the implementation.

public class ConsoleOutput : IOutput
{
    public void Write(string content)
    {
        Console.WriteLine(content);
    }
}

Then you need to regsiter types with autofac container in your startup file ConfigureServices() method. You also need to modify the signature of the method as well.

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    var builder = new ContainerBuilder();
    builder.RegisterType<ConsoleOutput>()
        .As<IOutput>().InstancePerLifetimeScope();
    builder.Populate(services);
    var container = builder.Build();
    return container.Resolve<IServiceProvider>();
}

Now you have completed the configuration. You can use the IOutput in controller constructor like this.

private IOutput _outputImpl;
public HomeController(IOutput outputImpl)
{
    _outputImpl = outputImpl;
}

Happy Programming



Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



Subscribe


Copyright © 2017 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub