Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IHttpClientFactory DI registration in .NET Framework with Autofac

.NET Framework Version: 4.7.2 Autofac Version: 4.0.1.0

I want to register IHttpClientFactory in my Global.asax but I can't use services.AddHttpClient like in .net core. I need IHttpClientFactory as a dependency for a http client class of my own that I need to reference in my webapi project.

Is this even possible? And if yes, how is it done?

like image 390
Arhire Ionut Avatar asked Sep 13 '19 13:09

Arhire Ionut


1 Answers

The required component are available in .Net Framework

Create a service collection, invoke add http client extension and use autofac integration Autofac.Extensions.DependencyInjection to populate your container and get a provider

The following .Net Framework Unit Test is used to demonstrate what was mentioned above

using System;
using System.Net.Http;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;

[TestClass]
public class HttpClientFactoryTest {
    [TestMethod]
    public void Should_Create_HttpClientFactory() {
        var services = new ServiceCollection(); //Create a service collection
        services.AddHttpClient(); //invoke add http client extension

        //...add other services as needed

        //use autofac integration `Autofac.Extensions.DependencyInjection` 
        var providerFactory = new AutofacServiceProviderFactory();
        //to populate your container
        ContainerBuilder builder = providerFactory.CreateBuilder(services);

        //...configure builder as needed

        //and get a service provider
        IServiceProvider serviceProvider = providerFactory.CreateServiceProvider(builder);

        IHttpClientFactory factory = serviceProvider.GetRequiredService<IHttpClientFactory>();

        //OR Container
        ContainerBuilder builder2 = providerFactory.CreateBuilder(services);

        //...configure builder as needed

        IContainer container = builder2.Build();

        IHttpClientFactory factory2 = container.Resolve<IHttpClientFactory>();
    }
}

and be easily reproduced in your Global.asax

like image 109
Nkosi Avatar answered Oct 09 '22 21:10

Nkosi