Reputation: 85
I know you can register an IAsyncPolicy<HttpResponseMessage>
to a particular instance of an HttpClient
injected into a service, but is there a way to configure this globally, to all HttpClients wired up via microsofts dependency injection?
For example, you can wire up the HttpClient injected into MyService
via:
services.AddHttpClient<MyService>(
.AddPolicyHandler(
HttpPolicyExtensions
.HandleTransientHttpError()
.WaitAndRetryAsync(3, retryAttempt =>
TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
But I would like to add this policy handler to all HttpClients. The class that I would like to add retries to is 3rd party and marked as internal, so I cannot directly access it.
Upvotes: 1
Views: 2962
Reputation: 22829
In short: With a custom HttpClientFactory you can but should not aim for this.
In order to use retry against an endpoint all these prerequisites should be met:
If we are talking about a REST API then implementing all CRUD operations in an idempotent is feasible but quite challenging to do it in a right way. So, most of the time you want to apply retry logic against only your retrieve calls, not against your data manipulation calls.
Also be aware that retries can make things even worse. If the downstream system is overloaded then sending new requests will not help the self-healing. Most probably it needs some "air" to go back to normal state from degraded. That's where Circuit Breaker might be helpful to avoid flooding downstream systems when it is already having hard time.
You can combine Retry and Circuit Breaker policies via escalation
Upvotes: 1