0

您好,我正在使用IHttpClientFactorywithDI来创建 附加HttpClient了自定义的实例。DelegatingHandler这些处理程序包含应处置的资源。就我而言,它们包含一个Pollypolicy 。

使用其委托处理程序处置此类 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;
} 
4

0 回答 0