.NET 框架版本:4.7.2
Autofac 版本:4.0.1.0
我想在我的 Global.asax 中注册 IHttpClientFactory 但我不能像在 .net core 中那样使用 services.AddHttpClient 。我需要 IHttpClientFactory 作为我自己的 http 客户端类的依赖项,我需要在我的 webapi 项目中引用它。
这甚至可能吗?如果是,它是如何完成的?
最佳答案
所需的组件在 .Net Framework 中可用
创建服务集合,调用添加 http 客户端扩展并使用 autofac 集成 Autofac.Extensions.DependencyInjection
填充您的容器并获取提供程序
下面的 .Net Framework 单元测试用于演示上面提到的内容
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>();
}
}
并在您的 Global.asax 中轻松复制
关于.net - 使用 Autofac 在 .NET Framework 中注册 IHttpClientFactory DI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57924995/