Getting started — How to use Autofac for dependency injection in .NET and .NET Core?
Autofac is an IoC container for .NET. It manages the dependencies between classes so that applications stay easy to change as they grow in size and complexity. Autofac is the most popular DI/IoC container for ASP.NET and it works with .NET Core flawlessly.
.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
1. NuGet: To use Autofac, you need to install below NuGet packages.
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
A module is a small class that can be used to bundle up a set of related components behind a ‘facade’ to simplify configuration and deployment. The module exposes a deliberate, restricted set of configuration parameters that can vary independently of the components used to implement the module.
- 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 (github.com)
Summary
.NET Core built-in IoC container may eliminate some complexity and easy to configure but may require a bit of extra coding in some cases. It all can be justified on smaller projects. When on large-scale projects having rich functionality of Autofac brings much more benefits and it may become irreplaceable.