Implementing Automated Dependency Injection with Autofac in .NET Core

To integrate Autofac into a .NET Core application, you must first include the Autofac and Autofac.Extensions.DependencyInjection NuGet packages in you're project.

Configuration

Modify the Program.cs file to instruct the host to use the Autofac service provider factory. This is achieved by chaining the UseServiceProviderFactory method during host construction:

public static IHostBuilder CreateHostBuilder(string[] args) =>
   Host.CreateDefaultBuilder(args)
       .UseServiceProviderFactory(new AutofacServiceProviderFactory())
       .ConfigureWebHostDefaults(webBuilder => {
           webBuilder.UseStartup<Startup>();
       });

Dependency Registration

In your Startup.cs, implement the ConfigureContainer method. Autofac will automatically call this method to populate the container during the application lifecycle:

public void ConfigureContainer(ContainerBuilder builder)
{
   builder.RegisterModule<DependencyInjectionModule>();
}

Automated Registration Logic

Instead of manual registration, you can use a custom Module to scan assemblies and register services based on interface markers. Define enterfaces such as ITransientDependency, IScopedDependency, and ISingletonDependency to categorize your services:

public class DependencyInjectionModule : Module
{
   protected override void Load(ContainerBuilder builder)
   {
       var assemblies = AppDomain.CurrentDomain.GetAssemblies();

       // Scoped Services
       builder.RegisterAssemblyTypes(assemblies)
           .Where(t => typeof(IScopedDependency).IsAssignableFrom(t) && !t.IsInterface)
           .AsImplementedInterfaces()
           .InstancePerLifetimeScope()
           .PropertiesAutowired();

       // Transient Services
       builder.RegisterAssemblyTypes(assemblies)
           .Where(t => typeof(ITransientDependency).IsAssignableFrom(t) && !t.IsInterface)
           .AsImplementedInterfaces()
           .InstancePerDependency()
           .PropertiesAutowired();

       // Singleton Services
       builder.RegisterAssemblyTypes(assemblies)
           .Where(t => typeof(ISingletonDependency).IsAssignableFrom(t) && !t.IsInterface)
           .AsImplementedInterfaces()
           .SingleInstance()
           .PropertiesAutowired();
   }
}

By implementing these marker interfaces in you're service classes, Autofac will automatically discover and register them with the appropriate lifestyle, while PropertiesAutowired() ensures that property-based dependency injection is enabled throughout your services.

Tags: autofac Dependency Injection IoC NET Core

Posted on Fri, 22 May 2026 21:35:16 +0000 by lingo5