Network failures happen. Polly adds retry, circuit breaker, and timeout policies automatically.
Install:
dotnet add package Polly dotnet add package Microsoft.Extensions.Http.Polly
Add to HttpClient:
// Program.cs
builder.Services.AddHttpClient("MyAPI", client =>
{
client.BaseAddress = new Uri("https://api.example.com");
})
.AddTransientHttpErrorPolicy(policy =>
policy.WaitAndRetryAsync(3, attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt)))
)
.AddTransientHttpErrorPolicy(policy =>
policy.CircuitBreakerAsync(5, TimeSpan.FromMinutes(1))
);
Usage:
public class MyService
{
private readonly IHttpClientFactory _factory;
public MyService(IHttpClientFactory factory)
{
_factory = factory;
}
public async Task GetDataAsync()
{
var client = _factory.CreateClient("MyAPI");
var response = await client.GetAsync("/data");
// Auto-retries on failure with exponential backoff
// Circuit breaks after 5 failures in a row
return await response.Content.ReadFromJsonAsync();
}
}
Resilient by default!
