您好,我正在使用IHttpClientFactory
withDI
来创建 附加HttpClient
了自定义的实例。DelegatingHandler
这些处理程序包含应处置的资源。就我而言,它们包含一个Polly
policy 。
使用其委托处理程序处置此类 HttpClient 实例的正确方法是什么?
Http 委托处理程序
class PollyDelegatingHandler:DelegatingHandler
{
private AsyncPolicyWrap<HttpResponseMessage> policy;
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return policy.ExecuteAsync(() =>
{
return base.SendAsync(request, cancellationToken);
});
}
public PollyDelegatingHandler(AsyncPolicyWrap<HttpResponseMessage> wrap)
{
this.policy = wrap;
}
}
HttpClient 创建
public HttpClient CreateHttpClient()
{
AsyncPolicyWrap<HttpResponseMessage> policy = pollyFactory.CreatePolicy();
var client = HttpClientFactory.Create(new PollyDelegatingHandler(policy));
return client;
}