Autofac in ASP.Net Core Web Application

Hello everyone, and welcome back to dotnetcorecentral. Its been a couple of months since I did my last post. I was busy with work and family commitment. Finally got some time to write a post. Today I will focus on how we can use Autofac as a DI container for ASP.Net Core application.

What is Autofac

Autofac is a dependency injection/inversion of control container used widely by .Net community. As of today, it has more than 26 million downloads in nuget.org. The main concept behind inversion of control is to let the caller decide how the dependencies are created, instead of the class deciding it. Therefore, the class never creates an instance, rather expects it to be passed by the caller.

Creating ASP.Net Core Application

Open Visual Studio 2017, go to File -> New -> Project. Select .Net Core -> ASP.NET Core Web Application. This will create a new ASP.Net Core web application.

Autofac in ASP.Net Core New Project

In addition, when the project template pop-up appears, select Web API.

Autofac Web API template selection

For more information on how to create your first ASP.Net Core Web Application, visit my blog https://dotnetcorecentral.com/blog/creating-first-asp-net-core-web-api-application/ .

Autofac Nuget Package

First of all, I will add the Autofac Nuget package to the newly created ASP.Net Core Web Application. Therefore, right-click on the project and select Manage Nuget Packages.. Once the Nuget package manager window pops up, in the Browse tab search for Autofac.

Autofac nuget package

Select the Autofac NuGet package and install it.

In addition, we will also install Autofac.Extensions.DependencyInjection nuget package.

Configuring Autofac as DI Container

After the NuGet packages are installed, we will add a couple of types to the project. We will add IDataProvider interface and DataProvider class. DataProvider class will return a static text.

namespace AutofacIntegration
{
    public interface IDataProvider
    {
        string Get();
    }
}

namespace AutofacIntegration
{
    public class DataProvider : IDataProvider
    {
        public string Get()
        {
            return "Test data";
        }
    }
}

Update to Startup.cs

The code in Startup class will change to use Autofac as the DI container. Firstly, we will add Autofac and Autofac.Extensions.DependencyInjection in the using statement. In addition, I will update the implementation of the ConfigureServices method.

using System;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace AutofacIntegration
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public IContainer ApplicationContainer { get; private set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // Create the container builder.
            var builder = new ContainerBuilder();
            builder.Populate(services);
            builder.RegisterType<DataProvider>().As<IDataProvider>();
            this.ApplicationContainer = builder.Build();

            // Create the IServiceProvider based on the container.
            return new AutofacServiceProvider(this.ApplicationContainer);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

Firstly, change the return type of the method ConfigureServices from void to IServiceProvider. In addition, use the ContainerBuilder class of Autofac to register the types. Finally call Build method on the ContainerBuilder and return a new instance of AutofacServiceProvider. The ASP.Net Core infrastructure will use the instance of AutofacServiceProvider as a DI container.

Running the application

Finally, I will update the default ValueController to use the IDataProvider to return the constant text “Test data” as a return to the Get method.

using Microsoft.AspNetCore.Mvc;

namespace AutofacIntegration.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly IDataProvider dataProvider;

        public ValuesController(IDataProvider dataProvider)
        {
            this.dataProvider = dataProvider;
        }

        // GET api/values
        [HttpGet]
        public string Get()
        {
            return dataProvider.Get();
        }
    }
}

Now run the application to see “Test data” in the browser.

Autofac integration response on browser

Conclusion

It is extremely easy to integrate Autofac as a dependency injection/inversion of control container to the ASP.Net Core application. Autofac provides a lot of advanced features and ease of using a DI container.

More information about Autofac: https://autofaccn.readthedocs.io/en/latest/index.html

Source code: https://github.com/choudhurynirjhar/AutofacIntegration