【发布时间】:2022-10-19 13:41:18
【问题描述】:
我知道您可以将IAsyncPolicy<HttpResponseMessage> 注册到注入到服务中的HttpClient 的特定实例,但是有没有办法全局配置它,通过微软的依赖注入连接到所有HttpClients?
例如,您可以通过以下方式连接注入MyService 的 HttpClient:
services.AddHttpClient<MyService>(
.AddPolicyHandler(
HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
但我想将此策略处理程序添加到所有 HttpClients。我想添加重试的类是第 3 方并标记为内部,所以我不能直接访问它。
【问题讨论】:
-
您不能,因为无法确定每个客户端的创建方式。但听起来你可能问错了问题。您是否需要一种在全球范围内添加重试的方法,或者您真的只需要一种将它们添加到第三方库的方法?
标签: c# dependency-injection dotnet-httpclient polly retry-logic