Configure HttpClientfactory using Autofac DI
Today in this article, we will see how to use Configure HttpClientfactory using Autofac DI Container in ASP.NET Core.
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.
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.
Today in this article, we will cover below aspects,
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 the DI approach like,
- Separation of concern
- Independently deployable unit
- Easily Testable units
- High performance
- Easy maintenance
Getting Started
- Open Visual Studio
- Let’s create an ASP.NET core API application.
Create ASP.NET Core API
Please choose any ASP.NET Core API project template. Filters are supported in most ASP.NET Core project templates,
PM> Install-Package Autofac.Extensions.DependencyInjection -Version <version>
OR
Use Nuget manager,
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 the 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 HttpClientfactory
Define Autofac DI Container with services as below in Startup.cs
public void ConfigureContainer(ContainerBuilder builder)
{
//Register your services
builder.RegisterType<BusinessLayer>().As<IBusinessLayer>();
builder.Register(c => c.Resolve<IHttpClientFactory>().CreateClient())
.As<HttpClient>();
}
The above code registers the IHttpClientFactory within the Autofac DI container instead of the built-in DI container.
Step 3 – Use HttpClientfactory using Dependency Injection
Please perform dependency Injection (DI) of HttpClientfactory and other required Services using Constructor Injection as shown below,
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly IBusinessLayer _businessLayer;
private readonly ILogger<WeatherForecastController> _logger;
private readonly IHttpClientFactory _clientFactory;
public WeatherForecastController(ILogger<WeatherForecastController> logger,
IBusinessLayer businessLayer,
IHttpClientFactory clientFactory)
{
_logger = logger;
_businessLayer = businessLayer;
_clientFactory = clientFactory;
}
[HttpGet]
public async Task<IActionResult> GetAsync()
{
var client = _clientFactory.CreateClient("TheCodeBuzz");
...
...
}
With the above configuration, you should be all set to use HttpClientfactory using Autofac DI.
References :
- Create Named HTTPClient using IHttpClientFactory in ASP.NET Core
- Typed HTTPClient using HttpClientFactory in ASP.NET Core -Part2
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.
“Consuming HttpClient as a dependency”
What’s the correct way?
class MyService
{
public MyService(IHttpClientFactory httpClientFactory) { }
}
or
class MyService
{
public MyService(HttpClient httpClient) { }
}
Hello Jose, Thanks for your query. It’s recommended using HttpClientfactory as it provides many advantages. If you want to use HttpClient still then please declare it as a shared static resource and use it without construction injection.
Please refer article of Using HTTPClient Best Practices and Anti-Patterns
Have a good day!