Search code examples
c#dependency-injectiondotnet-httpclient.net-7.0polly

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?


Solution

  • 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