Cannot Configure Flurl to use Polly PolicyHandler

705 Views Asked by At

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);
    }
}
1

There are 1 best solutions below

0
On

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