joydip_kanjilal
Contributor

How to use Autofac in ASP.Net Core

how-to
May 27, 20195 mins
Microsoft .NETSoftware Development

Take advantage of the Autofac inversion of control container to manage dependencies in your ASP.Net Core applications

abstract connections / network / object / root / inheritance / hierarchy
Credit: Koto Feja / Getty Images

Dependency injection facilitates loose coupling and promotes testability and maintenance. ASP.Net Core provides built-in support for dependency injection (a kind of inversion of control) with a minimalistic dependency injection container. However, the built-in container lacks many of the features of a full-fledged dependency injection or inversion of control container.

To overcome this, you can use third-party containers in ASP.Net Core. In other words, you can easily replace the built-in container with a third-party container. Autofac is an inversion of control container that can be used to resolve dependencies. This article provides a discussion of how we can work with Autofac in ASP.Net Core.

Create an ASP.Net Core project in Visual Studio

First let’s create an ASP.Net Core project in Visual Studio. Assuming Visual Studio 2017 or Visual Studio 2019 is installed in your system, follow the steps outlined below to create a new ASP.Net Core project in Visual Studio.

  1. Launch the Visual Studio IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.Net Core Web Application” from the list of the templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Click Create.
  7. In the “Create New ASP.Net Core Web Application” window, select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top.
  8. Select “Web Application” as the project template. 
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
  11. Click Create.

This will create a new ASP.Net Core project in Visual Studio. We’ll use this project in the subsequent sections of this article to work with Autofac.

Install Autofac in your ASP.Net Core project

It is easy to install Autofac – you can install it from NuGet. At the time of this writing, the current version of Autofac is 4.9.2. To work with Autofac, you should install the Autofac.Extensions.DependencyInjection package as well. This will ensure that you have the necessary dependencies installed for working with Autofac.

Select the ASP.Net Core Web Application project you created above, then right-click and install Autofac.Extensions.DependencyInjection via the NuGet Package Manager. Accept any licensing agreements you might be prompted for during the installation. Alternatively, you can install this package by entering the following command in the NuGet Package Manager Console:

Install-Package Autofac.Extensions.DependencyInjection

Create a class in your ASP.Net Core application

To illustrate dependency injection, we’ll need some objects to work with. Consider the IAuthorRepository interface that contains the declaration of the GetMessage method below.

 public interface IAuthorRepository
    {
        string GetMessage();
    }

The AuthorRepository class implements the IAuthorRepository interface as shown below.

 public class AuthorRepository : IAuthorRepository
    {
        public string GetMessage()
        {
            return "Hello World";
        }
    }

Note that this is a minimalistic implementation of a repository — i.e., it doesn’t contain the CRUD methods that a typical repository contains. I will leave it to you to implement the CRUD methods appropriately.

Configure Autofac in ASP.Net Core

To configure Autofac, you should specify the configuration code in the ConfigureServices method of the Startup class. Note that the ConfigureServices method is used to add services at runtime to the container.

The first step is to create a container builder to register the necessary services with the Autofac container. The first step is to populate the framework services using the Populate method as shown below.

var containerBuilder = new ContainerBuilder();
containerBuilder.Populate(services);

The next step is to register the custom services with Autofac. To do this, use the RegisterType method on the container builder instance as shown below.

containerBuilder.RegisterType<AuthorRepository>().As<IAuthorRepository>();

To build the container, write the following code.

var container = containerBuilder.Build();
return container.Resolve<IServiceProvider>();

Here is the complete source code of the ConfigureServices method for your reference:

public IServiceProvider ConfigureServices(IServiceCollection services)
   {
       services.AddMvc();
       var containerBuilder = new ContainerBuilder();
       containerBuilder.Populate(services);
       containerBuilder.RegisterType<AuthorRepository>().
       As<IAuthorRepository>();
       var container = containerBuilder.Build();
       return container.Resolve<IServiceProvider>();
   }

Use Autofac in your controllers in ASP.Net Core

Now that Autofac has been installed and configured in your project, you can get started using it in your controllers. The following code snippet illustrates how you can resolve dependencies in the ValuesController.

  public class ValuesController : ControllerBase
  {
        private IAuthorRepository _authorRepository; 
        public ValuesController(IAuthorRepository authorRepository) 
        {
            _authorRepository = authorRepository;
        }         // GET api/values
        [HttpGet]
        public ActionResult<string> Get()
        {
            return _authorRepository.GetMessage();
        }
     //Other action methods
  }

The dependency injection principle is a realization of the inversion of control principle. It is a technique that is used to remove dependencies from implementation by allowing you to inject these dependencies externally. Inversion of control containers such as Autofac take advantage of dependency injection to invert the flow of control and help to automate instantiation and lifecycle management of objects.

Dependency injection takes three forms: constructor injection, interface injection, and property injection. In this example, we used constructor injection to inject a dependency — namely an instance of type AuthorRepository — at runtime in the ValuesController class.

We’ve seen how Autofac can be used to replace the default dependency injection container in ASP.Net Core, but we’ve only scratched the surface of its capabilities. I will explore Autofac in more depth in future posts here.

joydip_kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author