inversion-of-controldotnet-httpclient.net-4.7.2httpclientfactoryihttpclientfactory

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?


Solution

  • 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);
    

    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.