Linked Questions

Popular Questions

IHttpClientFactory with Autofac in .NET 4.8

Asked by At

I came to a point where I needed to replace usage of HttpClient with IHttpClientFactory in order to reduce number of sockets that are in use and avoid socket exhaustion.

As preferable approach, I wanted to use IHttpClientFactory and register it by using Autofac, and I also wanted to confirm the difference between usage of HttpClient and IHttpClientFactory - how to know if my implementation is working properly?

My base implementation of the class that uses IHttpClientFactory goes something like this (one of the classes):

public class ImportHttpClient : IImportHttpClientAccessor
    {
        public HttpClient Client { get; }

        public ImportHttpClient(IHttpClientFactory httpClientFactory)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            Client = httpClientFactory.CreateClient();
            Client.BaseAddress = new Uri(GlobalVariables.ImportServiceSettings.BaseUrl);         
        }
    }

and registration of this class with Autofac is very straightforward:

builder.RegisterType<ImportHttpClient>().As<IImportHttpClientAccessor>().InstancePerLifetimeScope();

But, the registration of IHttpClientFactory remained the problem and also a test to compare before/after using IHttpClientFactory.

Related Questions