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