Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Dependency injection with AutoFac in ASP.NET 5

2.00/5 (1 vote)
31 Oct 2015MIT 6.6K  
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.

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

License

This article, along with any associated source code and files, is licensed under The MIT License