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?
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 IHttpClientFactoryThis sample uses SimpleInjector.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With