What it is
Autofac is a mature .NET IoC container offering features beyond the built-in one: assembly scanning, decorators, property injection and fine-grained lifetime scopes.
Register components in a ContainerBuilder with explicit lifetimes, then resolve. Integrates with ASP.NET Core as a replacement for the default provider.
Installation
dotnet add package AutofacGetting started
The smallest useful thing you can do with it, and what each part means.
var builder = new ContainerBuilder();
builder.RegisterType<BookService>().As<IBookService>().InstancePerLifetimeScope();
builder.RegisterType<SqlConnectionFactory>().As<IConnectionFactory>().SingleInstance();
// Convention-based: register everything ending in "Repository".
builder.RegisterAssemblyTypes(typeof(BookRepository).Assembly)
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
var container = builder.Build();
using var scope = container.BeginLifetimeScope();
var service = scope.Resolve<IBookService>();Advanced usage
Where the library earns its place over a simpler alternative.
builder.RegisterType<BookRepository>().As<IBookRepository>();
// Wrap it — callers still ask for IBookRepository and get the chain.
builder.RegisterDecorator<CachingBookRepository, IBookRepository>();
builder.RegisterDecorator<LoggingBookRepository, IBookRepository>();
// ASP.NET Core integration
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(b => b.RegisterModule<AppModule>());Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- No constructors on type can be invoked
- A constructor parameter is not registered. The message names the type — register it or add a parameter registration.
- Captive dependency: singleton holds a scoped service
- Widen the dependency's lifetime or narrow the consumer's. A singleton capturing a DbContext will use a disposed context.
Best practices
- Use the built-in container unless you specifically need decorators, scanning or property injection.
- Register with the narrowest lifetime that works; SingleInstance holding scoped state causes subtle bugs.
- Group registrations into Modules so the composition root stays readable.
- Resolve only at the composition root; injecting the container itself is a service locator.
Background
Why it exists, and what it was reacting to.
Autofac predates Microsoft's built-in container and remains in use where that container's deliberate simplicity is limiting — particularly for decorators and convention-based registration.
