I want to configure httpClient with Retry Policy in Autofac container. The below code does not initiate retry. Am I missing anything?
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);
});
}
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.
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>();
});