How to configure an polly policy for HttpClient in Autofac ContainerBuilder in .Net 6

401 Views Asked by At

I want to configure httpClient with Retry Policy in Autofac container. The below code does not initiate retry. Am I missing anything?

Policy definition

static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
    return HttpPolicyExtensions
        .HandleTransientHttpError()
        .OrResult(msg => msg.StatusCode != System.Net.HttpStatusCode.OK)
        .WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(retryAttempt),
        (exception, timeSpan, retryCount, context) =>
        {
            Task.Delay(5000);
        });
}

DI registration

var services = new ServiceCollection(); 
services.AddHttpClient(); 
var providerFactory = new AutofacServiceProviderFactory();

ContainerBuilder builder = providerFactory.CreateBuilder(services);

builder.Register(c => c.Resolve<IHttpClientBuilder>()
           .AddPolicyHandler(GetRetryPolicy()));

builder.Register(c => c.Resolve<IHttpClientFactory>().CreateClient())
   .As<HttpClient>();

The code doesn't error. It doesn't initiate retries.

2

There are 2 best solutions below

0
TechMama On BEST ANSWER

I used below code to register IhttpClientFactory with Polly policy in Autofac container.

 builder.Register<IHttpClientFactory>(_ =>
        {
            var services = new ServiceCollection();
            services.AddHttpClient("MyClient", client =>
            {
                client.BaseAddress = new Uri("https://myapi.com");
                client.DefaultRequestHeaders.Add("accept", "application/json");
            }).AddPolicyHandler(GetRetryPolicy());
                
            var provider = services.BuildServiceProvider();
            return provider.GetRequiredService<IHttpClientFactory>();
        });
0
Peter Csala On

I think you should call the AddPolicyHandler before you build the collection not after.

var services = new ServiceCollection(); 
services.AddHttpClient()
        .AddPolicyHandler(GetRetryPolicy()); 

var providerFactory = new AutofacServiceProviderFactory();
var builder = providerFactory.CreateBuilder(services);

builder.Register(c => c.Resolve<IHttpClientFactory>().CreateClient())
   .As<HttpClient>();

I would also suggest to take a look at this SO thread.