Skip to content

Use Autofac IoC Container in ASP.NET or ASP.NET Core

Getting started — How to use Autofac for dependency injection in .NET and .NET Core?



.NET Core gives you a built-in dependency injection framework. Though the default DI may offer enough functionality, there is a certain limitations like resolving a service with some associated Metadata, Named/Keyed services, Aggregate Services, Multi-tenant support, lazy instantiation, and much more. As the system grows you might need such features, and Autofac gives you all these features.

Configure Autofac in ASP.NET Core application

PM> Install-Package Autofac
PM> Install-Package Autofac.Extensions.DependencyInjection

2. Configuration: Configure Host builder, typically this is your Program.cs and insert .UseServiceProviderFactory(new AutofacServiceProviderFactory()). The core of the integration is the AutofacServiceProviderFactory. It enables Autofac as DI container in your ASP.NET Core Application.


3. Add a ConfigureContainer method to Startup class. ConfigureServices method is called by .NET Core at application startup time to register additional services. The ConfigureContainer method registers the components in the container using the container’s native APIs.



Autofac Module




4. Usage: You are done with Autofac configuration. Now for injecting the dependency, it is same code that we use using with default DI.



Autofac Modules Use Cases

  • Modular approach. New or customized mechanisms for configuring the container.
  • Register a number of similar services that are often used together.
  • Configure related services that provide a subsystem.
  • Package optional application features as ‘plug-ins’.
  • Provide pre-built packages for integration with a system.

Sample source code on nirzaf/AutoFacExamples (



Leave a Reply

Your email address will not be published. Required fields are marked *