3

I have a .NET HostedService which uses dependency injection. My client factory creates a policy handler and in DI I configure Flurl to use the factory. In debug mode I can see that clients are generated by the factory which use the TransientFaultPolicyHandler but I don't get any retries.

Program.cs

services.AddSingleton<IFlurlClientFactory, PerBaseUrlFlurlClientFactory>();

FlurlHttp.Configure(settings =>
{
    settings.HttpClientFactory = new PollyHttpClientFactory();    
});

PollyHttpClientFactory

public class PollyHttpClientFactory : DefaultHttpClientFactory
{
    public override HttpMessageHandler CreateMessageHandler()
    {
        return new TransientFaultPolicyHandler
        {
             InnerHandler = base.CreateMessageHandler()
        };
    }

    public override HttpClient CreateHttpClient(HttpMessageHandler handler)
    {
        return new HttpClient(CreateMessageHandler());
    }
}

TransientFaultPolicyHandler.cs

public class TransientFaultPolicyHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Policy.Handle<FlurlHttpException>()
            .WaitAndRetryAsync(3, attempt =>
            {
                var nextAttempt = TimeSpan.FromSeconds(Math.Pow(2, attempt));
                //$"Retry attempt {attempt} to make request. Next try on {nextAttempt.TotalSeconds} seconds.";
                return nextAttempt;
            })
            .ExecuteAsync(token => base.SendAsync(request, token), cancellationToken);
    }
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
phil
  • 1,938
  • 4
  • 23
  • 33
  • I'm not familiar with Flurl but why did you define the retry policy inside the `DelegatingHandler`? – Peter Csala May 03 '21 at 07:37
  • Mainly because I could and I was in a hurry to implement something. Never good coding in a rush I admit. – phil May 03 '21 at 11:53

1 Answers1

1

This does actually work. I was using an IDE that I'm not very familiar with and so couldn't see it being called.

phil
  • 1,938
  • 4
  • 23
  • 33