How do you override AddStandardResilenceHandler() for a specific client?

511 Views Asked by At

Given the following is set as the default for all clients in the C# project:

builder.Services.ConfigureHttpClientDefaults(http => {
    // Turn on resilience by default
    http.AddStandardResilienceHandler();

});

How does one override the values of that StandardResilienceHandler for a specific Client?

I've tried the following variations:

    services.AddHttpClient<IMyClient, MyClient>()           
        .AddResilienceHandler("MyClient", (context, next) => {
            context.AddTimeout(TimeSpan.FromMinutes(10));
        });

ignored

.AddStandardResilienceHandler(options => {
                options.AttemptTimeout = new HttpTimeoutStrategyOptions {
                    Timeout = TimeSpan.FromMinutes(5)
                };
                options.TotalRequestTimeout = new HttpTimeoutStrategyOptions {
                    Timeout = TimeSpan.FromMinutes(15)
                };
                options.CircuitBreaker.SamplingDuration = TimeSpan.FromMinutes(10);
            });

Also ignored.

I also created a policy like this:

var retryPolicy = HttpPolicyExtensions

                    .HandleTransientHttpError()
                    .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)))
                    .WrapAsync(Policy.TimeoutAsync<HttpResponseMessage>(
                        TimeSpan.FromMinutes(5),
                        TimeoutStrategy.Optimistic));

and then used this:

.AddPolicyHandler(retryPolicy)

It still uses the default no matter what.

You'd think this would be easy and documented but I can't find anything in search.

2

There are 2 best solutions below

0
On

As far as I know you can't do what you want to achieve.

Whenever you call AddStandardResilienceHandler or AddResilienceHandler it registers a brand new ResilienceHandler. That class is currently treated as internal. (So, calling it multiple times will register multiple ResilienceHandler instances.)

You might have the temptation to retrieve the -standard pipeline itself (that's the name of the pipeline which is registered by the AddStandardResilienceHandler call) through the ResiliencePipelineProvider<string>. The problem with that the retrieved ResiliencePipeline it not adjustable directly. It only supports reload but that won't help you either...

So all in all, currently this use case is not supported. I would recommend to file an issue on the https://github.com/dotnet/extensions/issues repository.

1
On

For those who haven't found an answer. Call Configure() :

.AddStandardResilienceHandler().
Configure(options => ...);