c# - 解析不同的HttpClient
问题描述
给定以下类:
public class HttpHelper
{
private readonly HttpClient client;
public HttpHelper(HttpClient client)
{
this.client = client;
}
}
public class ServiceA
{
private readonly HttpHelper helper;
public ServiceA(HttpHelper helper)
{
this.helper = helper;
}
}
public class ServiceB
{
private readonly HttpHelper helper;
public ServiceB(HttpHelper helper)
{
this.helper = helper;
}
}
和以下设置:
sc.AddSingleton<ServiceA>()
.AddHttpClient<HttpHelper>()
.ConfigureHttpClient((sp, client) => { client.BaseAddress = new Uri("http://domainA"); });
sc.AddSingleton<ServiceB>()
.AddHttpClient<HttpHelper>()
.ConfigureHttpClient((sp, client) => { client.BaseAddress = new Uri("http://domainB"); });
当我尝试解析 ServiceA 和 ServiceB 时,它们都获得了具有相同 URL 的 HttpClient。
如何更改 DI 中的注册,以便每个服务都获得正确的 HttpClient 注入?
TIA
/索伦
解决方案
我宁愿做这样的事情。
public class ServiceA
{
private readonly HttpClient httpClient;
public ServiceA(HttpClient httpClient)
{
this.httpClient = httpClient;
}
}
public class ServiceB
{
private readonly HttpClient httpClient;
public ServiceB(HttpClient httpClient)
{
this.httpClient = httpClient;
}
}
在配置服务中。
services.AddHttpClient<ServiceA>().ConfigureHttpClient(client =>
{
client.BaseAddress = new Uri("http://domainA");
});
services.AddHttpClient<ServiceB>().ConfigureHttpClient(client =>
{
client.BaseAddress = new Uri("http://domainB");
});
笔记 :
在你的情况下,有两件事是有问题的。
AddSingleton
对于ServiceA
和ServiceB
AddHttpClient<HttpHelper>
是问题,因为它变成单例并且只有一个被启动。
推荐阅读
- javascript - Android Javascript 接口无法接收回调函数
- javascript - 使用包装器 javascript 分组
- machine-learning - 在训练数据上使用 SMOTE
- python - 尝试通过python脚本打开png文件时,Applescript给出错误权限被拒绝
- javascript - 如果对象的类型只是“对象”,如何在 DevTools 内存快照中找到特定对象?
- c - 在同一结构中具有指向自身的指针的结构
- javascript - 数据表复选框在匹配的 id 上选择多个
- android - 来自智能手机的客户端通过 HTTP Post 将他/她的用户名和密码发送到服务器,没有任何加密,可以吗?
- r - 使用 if / else if 需要在 R 中填充昵称
- swift - MKMapView 在 Swift 中缩小地图时没有聚类注释