Polly 创建没有 ServiceCollection 的 HttpClient (IHttpClientBuilder.AddPolicyHandler)

Nod*_*.JS 3 c# dependency-injection dotnet-httpclient polly .net-7.0

我正在尝试使用 的IHttpClientBuilder.AddPolicyHandler方法Microsoft.Extensions.Http.Polly创建内置 Polly 策略的 HttpClient 实例。但是,我没有使用 IoC 和 ServiceCollection。如何IHttpClientBuilder在没有 ServiceCollection 和 IoC 的情况下创建,以便我可以使用扩展方法AddPolicyHandler。即使我有 的实例IHttpClientBuilder,如何创建 HttpClient?

Pet*_*ala 6

您不需要使用 DI 来HttpClient用策略来装饰。您可以通过PolicyHttpMessageHandler. 这里的技巧是将InnerHandler设为HttpClientHandler

var policy = ...;
var policyHandler = new PolicyHttpMessageHandler(policy);
policyHandler.InnerHandler = new HttpClientHandler();   
var httpClient = new HttpClient(policyHandler);
//the usage of the httpClient
Run Code Online (Sandbox Code Playgroud)