Click here to Skip to main content
15,881,898 members
Articles / Web Development / HTML

Dependency injection with AutoFac in ASP.NET 5

Rate me:
Please Sign up or sign in to vote.
2.00/5 (1 vote)
31 Oct 2015MIT 6.5K   4   1
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


Written By
Technical Lead
India India
Working as Tech. Lead

My blog : dotnetthoughts.net.
You can follow me in twitter : @anuraj

Comments and Discussions

 
QuestionWhat about a trojan ? Pin
InvisibleMedia2-Nov-15 9:06
professionalInvisibleMedia2-Nov-15 9:06 
If I can change the implementation of everything...what about a trojan ?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.