liveBook · Manning

Microsoft.Extensions.Http.Polly

As explained in ASP.NET Core in Action, 3e

Microsoft.Extensions.Http.Polly is a .NET integration library that applies Polly resilience policies to HttpClient instances created by IHttpClientFactory.

Microsoft.Extensions.Http.Polly integrates Polly resilience policies with HttpClient instances created by IHttpClientFactory. It handles transient failures in the handler pipeline, so callers can use a resilient client without writing retry logic manually. section 33.3

Configure transient HTTP error handling in a few steps:

  • Install the Microsoft.Extensions.Http.Polly NuGet package. section 33.3
  • Register a named or typed client with AddHttpClient. section 33.3
  • Call AddTransientHttpErrorPolicy and provide a Polly policy, such as a retry policy waiting 200 milliseconds, 500 milliseconds, and one second between attempts. section 33.3
  • Review retry effects carefully: default handling covers connection errors, 5xx responses, and 408 timeouts, but retries should target only safe requests. section 33.5

Retrying an ExchangeRatesClient request

builder.Services.AddHttpClient<ExchangeRatesClient>() .AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(new[] { TimeSpan.FromMilliseconds(200), TimeSpan.FromMilliseconds(500), TimeSpan.FromSeconds(1) })); If a transient network problem or server error occurs, the handler retries before returning failure to the caller. section 33.3

Figure 33.5 Using the PolicyHttpMessageHandler to handle transient errors. If an error occurs when calling the remote API, the Polly handler will automatically retry the request. If the request then succeeds, the result is passed back to the caller. The caller didn’t have to handle the error, making it simpler to use the HttpClient while remaining resilient to transient errors.
CH33_F05_Lock3

Shows how PolicyHttpMessageHandler retries a failed remote request and passes a successful result back through the HttpClient pipeline. section 33.3

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains package setup, handler-pipeline behavior, retry configuration, handled errors, and alternative resilience strategies without detailing each Polly strategy.
Examples
Uses an ExchangeRatesClient with waits of 200 milliseconds, 500 milliseconds, and one second between retries.
What it assumes
Assumes familiarity with HttpClient and IHttpClientFactory while introducing package installation, typed clients, named clients, and Polly policies.
What you can do after
Operate/configure resilient HttpClient instances with automatic transient-error retries through AddTransientHttpErrorPolicy.
How it connects
Connects IHttpClientFactory, HttpClient, Polly policies, typed clients, named clients, and circuit breakers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.