我正在努力让 DI 在 autofac 中为 IHttpClientFactory 工作。
通常我使用 .net core 依赖注入(inject)系统,我这样做:
services.AddHttpClient(HttpClientConstants.HttpClientNameA, client =>
{
client.BaseAddress = new Uri(MyConfig.MyBaseUrl);
});
但是,现在我正在处理一个使用 Autofac 的 Net 框架项目。我在互联网上查找过,根据我发现的教程,我已经尝试过:
builder.Register(ctx => new HttpClient() { BaseAddress = new Uri(MyConfig.MyBaseUrl) })
.Named<HttpClient>(HttpClientConstants.HttpClientNameA)
.SingleInstance();
builder.Register(c => c.Resolve<IHttpClientFactory>().CreateClient())
.As<HttpClient>();
builder.RegisterType<MyService>().As<IMyService>();
但是当我尝试像这样使用它时,它崩溃了,我收到一个 Autofac 错误,指出它找不到构造函数来构建我的服务。
public class MyService: IMyService
{
private readonly IHttpClientFactory httpClientFactory;
public MyService(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
}
}
知道如何让它工作吗?我什至有可能或根本不应该使用 IHttpClientFactory 并使用不同的方法吗? (就像将 httpclient 直接注入(inject)到构造函数中一样)
最佳答案
我已经通过这种方式成功在 .netStandard 2.0 库中注册工厂:
containerBuilder.Register<IHttpClientFactory>(_ =>
{
var services = new ServiceCollection();
services.AddHttpClient();
var provider = services.BuildServiceProvider();
return provider.GetRequiredService<IHttpClientFactory>();
});
ServiceCollection 位于命名空间“Microsoft.Extensions.DependencyInjection”中,应使用 this nuget package 在 .net 框架中可用。 .
关于c# - 如何将 IHttpClientFactory 与 Autofac 一起使用(使用网络框架)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73608744/