Take advantage of the Autofac inversion of control container to manage dependencies in your ASP.Net Core applications
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.
- Launch the Visual Studio IDE.
- Click on “Create new project.”
- In the “Create new project” window, select “ASP.Net Core Web Application” from the list of the templates displayed.
- Click Next.
- In the “Configure your new project” window, specify the name and location for the new project.
- Click Create.
- 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.
- Select “Web Application” as the project template.
- Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
- Ensure that Authentication is set as “No Authentication” as we won’t be using authentication either.
- 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.