docs icon indicating copy to clipboard operation
docs copied to clipboard

Adding examples of using Microsoft.Extensions.Http.Resilience outside a DI container

Open AlthalusDGr8 opened this issue 1 year ago • 2 comments

Type of issue

Missing information

Description

I am building a client library that uses an HttpClient internally and would like to add RetryPolicies. However, all examples at the moment present the information running under a condition where a DI services container is present. I would like to know how I can add resiliency to this client without having to request the user of the library to make use of DI.

Thanks!

Page URL

https://learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience?tabs=dotnet-cli

Content source URL

https://github.com/dotnet/docs/blob/main/docs/core/resilience/http-resilience.md

Document Version Independent Id

d3e3df15-0bd7-bbd4-6835-caf4c90543da

Article author

@IEvangelist

Metadata

  • ID: 1c92502c-2cdc-638e-484e-b5d1a9841ca2
  • Product: dotnet-fundamentals

AlthalusDGr8 avatar Dec 07 '23 11:12 AlthalusDGr8

The example for using Microsoft.Extensions.Http.Polly without DI is given here: https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines#resilience-policies-with-static-clients

We cannot change it to Microsoft.Extensions.Http.Resilience at the moment, due to ResilienceHandler not being publicly available yet, but the PR is already up https://github.com/dotnet/docs/pull/39010

We might want to add a link to that section to https://learn.microsoft.com/en-us/dotnet/core/resilience/http-resilience to help with discoverability.

CarnaViire avatar Jan 09 '24 12:01 CarnaViire

There was a recent PR in dotnet/extensions that makes this possible: https://github.com/dotnet/extensions/pull/4858

Another PR updates the section on resilience and static clients: https://github.com/dotnet/docs/pull/39010

One thing that not possible is to add standard resilience with static clients. Essentially you need to do something like this:

  HttpStandardResilienceOptions options = new();

  var pipeline = new ResiliencePipelineBuilder<HttpResponseMessage>()
      .AddRateLimiter(options.RateLimiter)
      .AddTimeout(options.TotalRequestTimeout)
      .AddRetry(options.Retry)
      .AddCircuitBreaker(options.CircuitBreaker)
      .AddTimeout(options.AttemptTimeout)
      .Build();

var socketHandler = new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(15) };
var resilienceHandler = new ResilienceHandler(pipeline)
{
    InnerHandler = socketHandler,
};

Note that example above is missing some benefits of using AddStandardResilienceHandler extension such as:

  • Automatic validation of HttpStandardResilienceOptions on startup.
  • Support for dynamic reloads when HttpStandardResilienceOptions are changed.
  • Logging and metering that are automatically wired when using DI.

martintmk avatar Jan 09 '24 12:01 martintmk