How to use Autofac in ASP.Net Core

By FoxLearn 1/3/2025 8:20:50 AM   76
Dependency injection in ASP.Net Core helps achieve loose coupling, enhancing testability and maintainability.

While ASP.Net Core offers built-in support for dependency injection through a minimal container, it lacks the advanced features found in more fully-featured dependency injection or inversion of control containers.

To address the limitations of the built-in container, you can replace it with a third-party container in ASP.Net Core. Autofac is one such inversion of control container that can be used to manage and resolve dependencies.

To install Autofac, use NuGet to add the Autofac.Extensions.DependencyInjection package, which ensures the necessary dependencies are included.

Right-click on your ASP.Net Core Web Application project, select "Install" via the NuGet Package Manager, and accept any licensing agreements.

Alternatively, you can install the package using the NuGet Package Manager Console.

Install-Package Autofac.Extensions.DependencyInjection

To demonstrate dependency injection, let's consider a different example using the IBookService interface, which defines a method called GetBookDetails.

public interface IBookService
{
    string GetBookDetails();
}

Next, we implement the IBookService interface in the BookService class as follows:

public class BookService : IBookService
{
    public string GetBookDetails()
    {
        return "This is a sample book.";
    }
}

This is a simplified implementation of a service class that returns a static book message. The focus here is on demonstrating how to use dependency injection with Autofac, rather than implementing full business logic like CRUD operations.

Configuring Autofac in ASP.Net Core

To use Autofac, you need to configure it in the ConfigureServices method of your Startup class. The ConfigureServices method is where you register services for dependency injection.

First, create a container builder to register the necessary services:

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

Next, register the custom service (in this case, BookService) with Autofac:

containerBuilder.RegisterType<BookService>().As<IBookService>();

Finally, build the container and resolve the IServiceProvider:

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

Here is the complete ConfigureServices method with the Autofac configuration:

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

Using Autofac in Controllers

Now that Autofac is installed and configured, you can use it in your controllers. Below is an example of how to resolve dependencies in the BooksController:

public class BooksController : ControllerBase
{
    private IBookService _bookService; 
    
    public BooksController(IBookService bookService)
    {
        _bookService = bookService;
    }

    // GET api/books
    [HttpGet]
    public ActionResult<string> Get()
    {
        return _bookService.GetBookDetails();
    }

    // Other action methods
}

In this example, we used constructor injection to inject the BookService dependency into the BooksController. Autofac, as an IoC container, helps automate the process of dependency resolution and lifecycle management.

Dependency injection (DI) is an application of the inversion of control (IoC) principle, which allows external injection of dependencies to decouple components. IoC containers like Autofac use DI to manage object instantiation and lifecycle. DI can be implemented in three ways: constructor injection, interface injection, and property injection.