I am trying to use IHttpClientBuilder.AddPolicyHandler method of Microsoft.Extensions.Http.Polly to create an instance of HttpClient with Polly policies built-in. However, I am not using an IoC and ServiceCollection. How to create IHttpClientBuilder without ServiceCollection and IoC so I can use the extension method AddPolicyHandler. Even If I have an instance of IHttpClientBuilder, how to create a HttpClient?
You don't need to have DI to decorate an HttpClient with a policy. You can do that via the PolicyHttpMessageHandler. The trick here is to set the InnerHandler to HttpClientHandler.
var policy = ...;
var policyHandler = new PolicyHttpMessageHandler(policy);
policyHandler.InnerHandler = new HttpClientHandler();
var httpClient = new HttpClient(policyHandler);
//the usage of the httpClient
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With