300
CHAPTER 7 | Implement resilient applications
Another issue that developers run into is when using a shared instance of
HttpClient
in long-running
processes. In a situation where the HttpClient is instantiated as a singleton or a static object, it fails to
handle the DNS changes as described in this
issue
of the dotnet/runtime GitHub repository.
However, the issue isn’t really with
HttpClient
per se, but with the
default constructor for HttpClient
,
because it creates a new concrete instance of
HttpMessageHandler
, which is the one that has
sockets
exhaustion
and DNS changes issues mentioned above.
To address the issues mentioned above and to make
HttpClient
instances manageable, .NET Core
2.1 introduced two approaches, one of them being
IHttpClientFactory
. It’s an interface that’s used
to
configure and create
HttpClient
instances in an app through Dependency Injection (DI). It also
provides extensions for Polly-based middleware to take advantage of delegating handlers in
HttpClient.
The alternative is to use
SocketsHttpHandler
with configured
PooledConnectionLifetime
. This
approach is applied to long-lived,
static
or singleton
HttpClient
instances. To learn more about
different strategies, see
HttpClient guidelines for .NET
.
Polly
is a transient-fault-handling library that helps developers add resiliency to their applications, by
using some pre-defined policies in a fluent and thread-safe manner.
Dostları ilə paylaş: