Gonçalo Castilho
Gonçalo Castilho

Reputation: 21

Overriding the HttpClientFactory policies defined with Polly

From .net Core 2+ MS gave us a way to add policies to the HttpClient that will work as long as the client is injected through the IOC container. But this led me to a doubt I can't seem to figure out while endlessly googling. What if we want to override the HttpClient policies while still using the HttpClientFactory and DI to inject the client into a provider? Can we "turn off" the policies for a specific request or can we add extra Policies while overriding the global ones defined on the Startup ?

Upvotes: 1

Views: 2596

Answers (1)

mountain traveller
mountain traveller

Reputation: 8156

Use different named clients or typed clients to define separate logical HttpClient configurations.

OR

When configuring policies using IHttpClientFactory, you can use .AddPolicyHandler(...) overloads or .AddPolicyHandlerFromRegistry(...) overloads which allow you to select the policy based on information in the HttpRequestMessage. This can permit varying the policies applied for different requests.

To take an example from the Polly and HttpClientFactory documentation, one use case might be to apply a Retry policy only to GET requests but not other http verbs:

var retryPolicy = HttpPolicyExtensions
    .HandleTransientHttpError()
    .WaitAndRetryAsync(new[]
    {
        TimeSpan.FromSeconds(1),
        TimeSpan.FromSeconds(5),
        TimeSpan.FromSeconds(10)
    });
var noOpPolicy = Policy.NoOpAsync().AsAsyncPolicy<HttpResponseMessage>();

services.AddHttpClient(/* etc */)
    // Select a policy based on the request: retry for Get requests, noOp for other http verbs.
    .AddPolicyHandler(request => request.Method == HttpMethod.Get ? retryPolicy : noOpPolicy);

Upvotes: 4

Related Questions