简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM