static IAsyncPolicy GetRetryPolicy
()
{
return HttpPolicyExtensions
.
HandleTransientHttpError
()
.
OrResult
(msg => msg.
StatusCode
== System.
Net
.
HttpStatusCode
.
NotFound
)
.
WaitAndRetryAsync
(
6
, retryAttempt => TimeSpan.
FromSeconds
(Math.
Pow
(
2
,
retryAttempt)));
}
You can find more details about using Polly in the
Next article
.
HttpClient lifetimes Each time you get an
HttpClient
object from the
IHttpClientFactory
, a new instance is returned.
But each
HttpClient
uses an
HttpMessageHandler
that’s pooled and reused by the
IHttpClientFactory
to reduce resource consumption, as long as the
HttpMessageHandler
’s lifetime
hasn’t expired.
Pooling of handlers is desirable as each handler typically manages its own underlying HTTP
connections; creating more handlers than necessary can result in connection delays. Some handlers
also keep connections open indefinitely, which can prevent the handler from reacting to DNS
changes.
The
HttpMessageHandler
objects in the pool have a lifetime that’s the length of time that an
HttpMessageHandler
instance in the pool can be reused. The default value is two minutes, but it can
be overridden per Typed Client. To override it, call
SetHandlerLifetime()
on the
IHttpClientBuilder
that’s returned when creating the client, as shown i
n the following code:
//Set 5 min as the lifetime for the HttpMessageHandler objects in the pool used for the
Catalog Typed Client
builder.
Services
.
AddHttpClient
()
.
SetHandlerLifetime
(TimeSpan.
FromMinutes
(
5
));
Each Typed Client can have its own configured handler lifetime value. Set the lifetime to
InfiniteTimeSpan
to disable handler expiry.