【发布时间】:2021-02-18 14:08:12
【问题描述】:
鉴于众所周知的使用 HttpClient 的困境和问题 - 即套接字耗尽和不尊重 DNS 更新,它被认为是使用 IHttpClientFactory 并让容器决定何时以及如何利用 http 池连接效率的最佳实践。这一切都很好,但现在我无法在每个请求上使用自定义数据实例化自定义 DelegatingHandler。
下面是我在使用工厂方法之前的操作示例:
public class HttpClientInterceptor : DelegatingHandler
{
private readonly int _id;
public HttpClientInterceptor(int id)
{
_id = id;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// associate the id with this request
Database.InsertEnquiry(_id, request);
return await base.SendAsync(request, cancellationToken);
}
}
每次我实例化一个 HttpClient 时,都可以传递一个 Id:
public void DoEnquiry()
{
// Insert a new enquiry hypothetically
int id = Database.InsertNewEnquiry();
using (var http = new HttpClient(new HttpClientInterceptor(id)))
{
// and do some operations on the http client
// which will be logged in the database associated with id
http.GetStringAsync("http://url.com");
}
}
但现在我无法实例化 HttpClient 和处理程序。
public void DoEnquiry(IHttpClientFactory factory)
{
int id = Database.InsertNewEnquiry();
var http = factory.CreateClient();
// and now??
http.GetStringAsync("http://url.com");
}
如何使用工厂实现类似的效果?
【问题讨论】:
-
您是否有理由要求新的客户端,而不是让框架通过依赖注入为您处理它?例如。
public void DoEnquiry(HttpClient client) -
@Jimenemex
IHttpClientFactory现在是大多数情况下的正确选择 (see here) -
另一种解决方案是以某种方式关闭 HttpClient 的底层连接,以便释放套接字连接。但在这附近找不到任何东西
标签: c# .net-core dotnet-httpclient