IHttpClientFactory for full framework (4.7) and IoC

1.9k views Asked by At

I am trying to Register IHttpClientFactory in Full Framework 4.7 (not core). I am using IoC container (LightInject)

Problem, that I do not have direct access to implementation of internal class DefaultHttpClientFactory https://github.com/dotnet/runtime/blob/master/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs This class is not visible because it is not public. I found solution as 3rd party implementation - https://github.com/uhaciogullari/HttpClientFactoryLite , bit it uses its own interface.

Is it possible to use interface IHttpClientFactory with IoC for Full Framework(not .net core)?

In case it is possible , what class can i use as implementation for IHttpClientFactory during registration for IoC?

1

There are 1 answers

0
Peter Csala On BEST ANSWER

As it was suggested in this github issue you can use this:

var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
container.RegisterInstance(serviceProvider.GetService<IHttpClientFactory>());
container.ContainerScope.RegisterForDisposal(serviceProvider);
  • AddHttpClient registers the DefaultHttpClientFactory for IHttpClientFactory
  • Then you can retrieve it from the DI container

This sample uses SimpleInjector but the same concept can be applied for any other DI framework.