Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHttpClientFactory for full framework (4.7) and IoC

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?

like image 261
Sergey Surnin Avatar asked Oct 28 '25 04:10

Sergey Surnin


1 Answers

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.

UPDATED

This is the same example using Castle Windsor DI framework:

var serviceProvider = new ServiceCollection().AddHttpClient().BuildServiceProvider();
container.Register(
    Castle.MicroKernel.Registration.Component.For<IHttpClientFactory>()
        .Instance(serviceProvider.GetService<IHttpClientFactory>())
        .LifestyleSingleton()
    );

And the same concept can be applied for any other DI framework.

like image 169
Peter Csala Avatar answered Oct 30 '25 13:10

Peter Csala