Last active
July 17, 2022 11:03
-
-
Save Azaferany/3611e2e816287e1fe5d63b629cbbb4cb to your computer and use it in GitHub Desktop.
add handler to all http client (Configuring ALL HttpClients named or unnamed)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Http; | |
using Microsoft.Extensions.Options; | |
using Polly; | |
using Prometheus; | |
var services = new ServiceCollection(); | |
services.AddSingleton<IHttpMessageHandlerBuilderFilter, DefaultHttpMessageHandlerBuilderFilter>(); | |
// added handlers to this client will apply to all http clients | |
services.AddHttpClient(DefaultHttpMessageHandlerBuilderFilter.GlobalMessageHandlerConfigure) | |
.AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(60))) | |
.AddPolicyHandler(Policy.TimeoutAsync<HttpResponseMessage>(10)); | |
services.AddHttpClient("example", client => client.BaseAddress = new Uri("http://example.com")) | |
.UseHttpClientMetrics(); | |
var provider = services.BuildServiceProvider(); | |
var httpClientFactory = provider.GetRequiredService<IHttpClientFactory>(); | |
//http client with Polly Retry + Polly Timeout + Prometheus-net Metrics | |
var httpClient = httpClientFactory.CreateClient("example"); | |
httpClient.GetAsync("/"); | |
/// <summary> | |
/// add all handlers of GlobalMessageHandlerConfigure client to all clients | |
/// https://github.com/dotnet/AspNetCore.Docs/issues/18162 | |
/// </summary> | |
public class GlobalHttpMessageHandlerBuilderFilter : IHttpMessageHandlerBuilderFilter | |
{ | |
public const string GlobalMessageHandlerConfigure = nameof(GlobalMessageHandlerConfigure); | |
public Action<HttpMessageHandlerBuilder> Configure(Action<HttpMessageHandlerBuilder> next) => | |
handlerBuilder => | |
{ | |
next(handlerBuilder); | |
if (handlerBuilder.Name != GlobalMessageHandlerConfigure) | |
{ | |
var clientFactoryOptions = handlerBuilder.Services | |
.GetRequiredService<IOptionsMonitor<HttpClientFactoryOptions>>().Get(GlobalMessageHandlerConfigure); | |
if (clientFactoryOptions is not null) | |
foreach (var builderAction in clientFactoryOptions.HttpMessageHandlerBuilderActions) | |
builderAction(handlerBuilder); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment