To integrate Autofac with .NET Core:
- Install the Autofac.Extensions.DependencyInjection NuGet package
- 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();
}
}