Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polly create HttpClient (IHttpClientBuilder.AddPolicyHandler) without ServiceCollection

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?

like image 668
Node.JS Avatar asked Oct 31 '25 05:10

Node.JS


1 Answers

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
like image 88
Peter Csala Avatar answered Nov 01 '25 19:11

Peter Csala



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!