The HttpClient factory is a pattern for configuring and retrieving named HttpClients in a composable way. This package integrates IHttpClientFactory with the Polly library, to add transient-fault-handling and resiliency through fluent policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback. This package was built from the source code at https://github.com/dotnet/dotnet/tree/87bc0b04e21d786669142109a5128c95618b75ed
$ dotnet add package Microsoft.Extensions.Http.PollyMicrosoft.Extensions.Http.Polly integrates IHttpClientFactory with the Polly library to provide comprehensive resilience and transient fault-handling. It allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner.
[!NOTE] This package is deprecated. Please use either
Microsoft.Extensions.ResilienceorMicrosoft.Extensions.Http.Resilienceinstead.
To use Microsoft.Extensions.Http.Polly, follow these steps:
dotnet add package Microsoft.Extensions.Http.Polly
AddTransientHttpErrorPolicy can be used define a policy that handles transient errors:
builder.Services.AddHttpClient("PollyWaitAndRetry")
.AddTransientHttpErrorPolicy(policyBuilder =>
policyBuilder.WaitAndRetryAsync(
retryCount: 3,
retryNumber => TimeSpan.FromMilliseconds(600)));
In the preceding example, failed requests are retried up to three times with a delay of 600 ms between attempts.
To dynamically inspect a request and decide which policy apply, use the AddPolicyHandler extension method:
var timeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(10));
var longTimeoutPolicy = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(30));
builder.Services.AddHttpClient("PollyDynamic")
.AddPolicyHandler(httpRequestMessage =>
httpRequestMessage.Method == HttpMethod.Get
? timeoutPolicy
: longTimeoutPolicy);
In this example, if the outgoing request is an HTTP GET, a 10-second timeout is applied. For any other HTTP method, a 30-second timeout is used.
The main types provided by this package are:
PollyHttpClientBuilderExtensions: Provides extension methods for configuring PolicyHttpMessageHandler message handlers as part of an HttpClient message handler pipelinePolicyHttpMessageHandler: A DelegatingHandler implementation that executes request processing surrounded by a Polly.PolicyPollyServiceCollectionExtensions: Provides convenience extension methods to register Polly.Registry.IPolicyRegistry<string> and Polly.Registry.IReadOnlyPolicyRegistry<string> in a service collectionHttpRequestMessageExtensions: Provides extension methods for HttpRequestMessage Polly integrationFor additional documentation and examples, refer to the official documentation on using Polly-based handlers in ASP.NET Core.
Microsoft.Extensions.Http.Polly is released as open-source under the MIT license. Bug reports and contributions are welcome at the GitHub repository.