Search code examples
winformsdependency-injectionhttpclientautofacihttpclientfactory

How to use IHttpClientFactory with .NET 4.8 without using DI from .NET Core/Standard


I've got a .NET 4.8 windows forms app which uses Autofac for DI. Currently, we're using a single HttpClient instance which is registered as a singleton:

 builder.Register(c => {
         var handler = c.Resolve<HttpClientHandler>();
         var bearerHandler = new BearerAuthenticationDelegatingHandler( c.Resolve<AuthenticationManager>(), handler);
         var client = new HttpClient(bearerHandler) {                                                                                            
             BaseAddress = new Uri(baseUrl)
         };
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         return client;
})
.AsSelf()
.SingleInstance();

AuthenticationManager is responsible for managing the access tokens which are injected into the web requests (BearerAuthenticationDelegatingHandler).

Even though I'm not being affected by DNS issues, I'd like to follow MS HttpClient recommendations and I'd like to add IHttpClientFactory to my app. However, it seems like there's simply no way to do that without adding a dependency to the dependency injection library which is typically used in .NET 7 projects (for instance, here's an example found of this approach).

So, is there any way to use IHttpClientFactory in .NET 4.8 projects without having to depend on the DI extension library?

Thanks.


Solution

  • So, is there any way to use IHttpClientFactory in .NET 4.8 projects without having to depend on the DI extension library?

    No, this is not possible. HttpClientFactory is tightly integrated with the MS DI infrastructure. This means that, in order to use it, you get into the painful situation that the following packages will be pulled in in your .NET 4.8 application:

    • Microsoft.Bcl.AsyncInterfaces
    • Microsoft.Extensions.DependencyInjection
    • Microsoft.Extensions.DependencyInjection.Abstractions
    • Microsoft.Extensions.Logging
    • Microsoft.Extensions.Logging.Abstractions
    • Microsoft.Extensions.Options
    • Microsoft.Extensions.Primitives
    • System.Buffers
    • System.Diagnostics.DiagnosticSource
    • System.Numeric.Vectors
    • System.Memory
    • System.Runtime.CompilerServices.Unsafe
    • System.Threading.Tasks.Extensions
    • System.ValueTuple

    Here is a related answer that shows how to use the HttpClientFactory outside the context of DI. You'll find that integrating it in your case will be similar to that method.

    I consider the hard dependency on the DI infrastructure a design flaw in the package containing HttpClientFactory.