Implementing Dependency Injection with Autofac in .NET Core

To integrate Autofac with .NET Core:

  1. Install the Autofac.Extensions.DependencyInjection NuGet package
  2. Replace the built-in DI contanier in Program.cs (Note: This transfers all existing registrations to Autofac)
// Replace default DI container with Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

Service Registration Patterns

Autofac supports three lifetime scopes:

  • Transient (default if not specified)
  • Scoped (InstancePerLifetimeScope)
  • Singleton (SingleInstance)
builder.Host.ConfigureContainer<ContainerBuilder>(builder => 
{
    builder.RegisterType<UserServiceImpl>().As<IUserService>().InstancePerLifetimeScope();
});

Generic Service Registration

For generic interfaces and implementations:

// Standard .NET Core registration
builder.Services.AddTransient(typeof(IBaseService<>), typeof(BaseService<>));

// Autofac registration
builder.Host.ConfigureContainer<ContainerBuilder>(builder => 
{
    builder.RegisterGeneric(typeof(BaseService<>)).As(typeof(IBaseService<>));
});

Property Injection

Enable property injection with PropertiesAutowired():

builder.Host.ConfigureContainer<ContainerBuilder>(builder => 
{
    builder.RegisterType<Service1>().As<IService1>().PropertiesAutowired();
});

Extension Methods for Cleaner Configuration

public static class AutofacExtensions
{
    public static void RegisterCoreServices(this ContainerBuilder builder)
    {
        builder.RegisterType<UserServiceImpl>().As<IUserService>().SingleInstance();
        builder.RegisterType<ScopedService>().As<IScopedService>().InstancePerLifetimeScope();
    }
}

Tags: autofac Dependency Injection .NET Core IoC Container

Posted on Mon, 18 May 2026 15:45:01 +0000 by johnoc