Search code examples
c#asp.net-coredotnet-httpclientpollyhealth-check

How can I add a Polly retry policy to AspNetCore.HealthChecks.Uris


How can I add a Polly retry policy to the AspNetCore.HealthChecks.Uris health check?

This health check is part of this repo: https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks

I see that I can use the configureClient and configurePrimaryHttpMessageHandler call backs when using healthCheckBuilder.AddUrlGroup.

However all the examples I see for using Polly require using IClientBuilder.AddPolicyHandler(...), but I can't figure out how to access IHttpClientBuilder when using healthCheckBuilder.AddUrlGroup.


Solution

  • The configurePrimaryHttpMessageHandler as its name suggests anticipates an HttpMessageHandler as a return value. This abstract class serves as a base class for many derived classes like DelegatingHandler or HttpClientHandler. Gladly Polly's HttpClient integrations are built upon DelegatingHandlers.

    Polly V7

    The AddPolicyHandler registers a PolicyHttpMessageHandler which is a DelegatingHandler. So, you can configure this class inside the configurePrimaryHttpMessageHandler callback.

    .ConfigurePrimaryHttpMessageHandler(() =>
    {
      return new PolicyHttpMessageHandler(policy)
      {
        InnerHandler = new HttpClientHandler()
      };
    });
    

    Polly V8

    Similarly, the AddResilienceHandler registers a ResilienceHandler which is a DelegatingHandler.

    .ConfigurePrimaryHttpMessageHandler(() =>
    {
      return new ResilienceHandler(pipeline)
      {
        InnerHandler = new HttpClientHandler()
      };
    });