302
CHAPTER 7 | Implement resilient applications
Figure 8-4. Using IHttpClientFactory with Typed Client classes.
In the above image, a
ClientService
(used by a controller or client code) uses an
HttpClient
created by the registered
IHttpClientFactory
.
This factory assigns an
HttpMessageHandler
from a
pool to the
HttpClient
. The
HttpClient
can be configured with Polly’s policies when registering the
IHttpClientFactory
in the DI container with the extension method
AddHttpClient
.
To configure
the above structure, add
IHttpClientFactory
in your application by installing the
Microsoft.Extensions.Http
NuGet package that includes the
AddHttpClient
extension method for
IServiceCollection
. This extension method registers the internal
DefaultHttpClientFactory
class to
be used as a singleton for the interface
IHttpClientFactory
. It defines a transient configuration for
the
HttpMessageHandlerBuilder
. This message handler (
HttpMessageHandler
object), taken from a
pool, is used by the
HttpClient
returned from the factory.
In the next snippet, you can see how
AddHttpClient()
can be used to register Typed Clients (Service
Agents) that need to use
HttpClient
.
// Program.cs
//Add http client services at ConfigureServices(IServiceCollection services)
builder.
Services
.
AddHttpClient
();
builder.
Services
.
AddHttpClient
();
builder.
Services
.
AddHttpClient
();
303
CHAPTER 7 | Implement resilient applications
Registering the client services as
shown in the previous snippet, makes the
DefaultClientFactory
create a standard
HttpClient
for each service. The typed client is registered as transient with DI
container. In
the preceding code,
AddHttpClient()
registers
CatalogService
,
BasketService
,
OrderingService
as transient services so they can be injected and consumed directly without any need
for additional registrations.
You could also add instance-specific configuration in the registration to, for example, configure the
base address, and add some resiliency policies, as shown in the following:
builder.
Services
.
AddHttpClient
(client =>
{
client.
BaseAddress
=
new
Uri
(builder.
Configuration
[
"BaseUrl"
]);
})
.
AddPolicyHandler
(
GetRetryPolicy
())
.
AddPolicyHandler
(
GetCircuitBreakerPolicy
());
In this next example, you can see the configuration of one of the above policies:
Dostları ilə paylaş: