DEV Community

Discussion on: .NET Core: Use HttpClientFactory and Polly to build rock solid services

Collapse
 
dimaaan profile image
Dmitry Anshilevich • Edited

Though Polly provides it out-of-the-box with reasonable defaults, you don't need 3rd party libraries to reuse retry logic with HttpClient.
Just extract it to DelegatingHandler

public class RetryHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        /* your retry logic ... */
    }
}
Enter fullscreen mode Exit fullscreen mode

and then add it to DI:

services.AddHttpClient(/*...*/).AddHttpMessageHandler<RetryHandler>();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
rickystam profile image
Ricky Stam

Hi Dmitry,

Thank you very much for your comment, it is a very nice addition to the post.
It is always nice to have more options on the table!

Collapse
 
dlidstrom profile image
Daniel Lidström

One advantage with Polly is that you can also enable ChaosMonkey (Simmy in Polly terms). I do this for all Polly policies and activate it for development only. Great way to test your resilience.