.NET 框架版本:4.7.2 Autofac 版本:4.0.1.0
我想在我的 Global.asax 中注册 IHttpClientFactory 但我不能像在 .net 核心中那样使用 services.AddHttpClient 。我需要 IHttpClientFactory 作为我自己的 http 客户端类的依赖项,我需要在我的 webapi 项目中引用它。
这甚至可能吗?如果是,它是如何完成的?
.NET 框架版本:4.7.2 Autofac 版本:4.0.1.0
我想在我的 Global.asax 中注册 IHttpClientFactory 但我不能像在 .net 核心中那样使用 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 中轻松复制