Configure Autofac Dependency Injection in ASP.NET Core
Today in this article, we will see how to Configure Autofac in ASP.NET Core application.
As we know .NET Core framework has leveraged the Explicit Dependency Injection (DI) principle very well and almost every functionality/service used in the application can be injected through DI.
Today in this article, we will cover below aspects,
Here Developers have a choice to use the default DI container framework provided by the application or use a custom DI solution like Autofac etc.
Container controls the lifetime of services used and the consumer need not have to worry about disposing of them once after every use.
There are a lot of benefits of DI approach like,
- Separation of concern
- Independently deployable unit
- Easily Testable units
- High performance
- Easy maintenance
Getting Started
- Open Visual Studio 2019
- Let’s create an ASP.NET core API application.
Create ASP.NET Core API
Please choose any ASP.NET Core API project template. Filter are supported in most ASP.NET Core project templates,
PM> Install-Package Autofac.Extensions.DependencyInjection -Version 7.1.0
OR
Step 1- Register HostBuilder to use Autofac Factory
Register the Generic Host Builder to use Autofac Factory.
In your Program.cs in the main method please add UseServiceProviderFactory extension and use the AutofacServiceProviderFactory.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Step 2- Define Autofac DI Container with services
Define Autofac DI Container with services as below in Startup.cs
public void ConfigureContainer(ContainerBuilder builder)
{
// Register your services
builder.RegisterType<BusinessLayer>().As<IBusinessLayer>();
}
Step 3 – Use Services using Dependency Injection
Please perform dependency Injection (DI) required Services using Constructor Injection.
public class WeatherForecastController : ControllerBase
{
private readonly IBusinessLayer _businessLayer;
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IBusinessLayer businessLayer)
{
_logger = logger;
_businessLayer = businessLayer;
}
[HttpGet]
public IActionResult Get()
{
var result = _businessLayer.PerformBusiness();
return Ok(result);
}
}
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.