Search code examples
c#autofacdotnet-httpclientpollyihttpclientfactory

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


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.


Solution

  • 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>();
            });