Configure HttpClientfactory using Autofac DI

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

  1. Open Visual Studio
  2. 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,

Configure Autofac DI Container in ASPNET Core 50

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 :

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.



2 thoughts on “Configure HttpClientfactory using Autofac DI

  1. “Consuming HttpClient as a dependency”

    What’s the correct way?

    class MyService
    {
    public MyService(IHttpClientFactory httpClientFactory) { }
    }

    or

    class MyService
    {
    public MyService(HttpClient httpClient) { }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *