How to leverage HttpClientFactory in older frameworks?

224 Views Asked by At

In .NET Framework 4.6, I cannot instantiate DefaultHttpClientFactory internal class to leverage port exhaustion and DNS change features of IHttpClientFactory.

I tried using the static instance of HttpClientFactory but there is no documentation on if it handles pooling of HttpMessageHandlers and their lifetimes.

1

There are 1 best solutions below

0
Angel Yordanov On

You can just use the Microsoft.Extensions.Http nuget package. It's netstandard2.0 and thus .NET Framework 4.6.1 compatible.

You can than use it by any of the methods described in the docs.

The only caveat is that you would need to use the new DI system, but that is pretty straightforward.

var services = new ServiceCollection();

services.AddHttpClient<MyHttpClient>(
    httpClient =>
    {
        httpClient.BaseAddress = new Uri("https://myapi.com");
    });

var serviceProvider = services.BuildServiceProvider();

var myHttpClient = serviceProvider.GetRequiredService<MyHttpClient>();