How to use HttpClientHandler with HttpClientFactory in .NET Core

前端 未结 2 1252
北荒
北荒 2021-01-03 23:13

I want to use the HttpClientFactory that is available in .NET Core 2.1 but I also want to use the HttpClientHandler to utilize the AutomaticD

2条回答
  •  迷失自我
    2021-01-03 23:55

    More properly to define primary HttpMessageHandler via ConfigurePrimaryHttpMessageHandler() method of HttpClientBuilder. See example below to configure typed client how.

    services.AddHttpClient()
        .ConfigureHttpClient((sp, httpClient) =>
        {
            var options = sp.GetRequiredService>().Value;
            httpClient.BaseAddress = options.Url;
            httpClient.Timeout = options.RequestTimeout;
        })
        .SetHandlerLifetime(TimeSpan.FromMinutes(5))
        .ConfigurePrimaryHttpMessageHandler(x => new HttpClientHandler() 
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
        })
        .AddHttpMessageHandler(sp => sp.GetService().CreateAuthHandler())
        .AddPolicyHandlerFromRegistry(PollyPolicyName.HttpRetry)
        .AddPolicyHandlerFromRegistry(PollyPolicyName.HttpCircuitBreaker);
    

    Also you can define error handling policy via usage of special builders methods of Polly library. In this example policy should be predefined and stored into policy registry service.

    public static IServiceCollection AddPollyPolicies(
        this IServiceCollection services, 
        Action setupAction = null)
    {
        var policyOptions = new PollyPoliciesOptions();
        setupAction?.Invoke(policyOptions);
    
        var policyRegistry = services.AddPolicyRegistry();
    
        policyRegistry.Add(
            PollyPolicyName.HttpRetry,
            HttpPolicyExtensions
                .HandleTransientHttpError()
                .WaitAndRetryAsync(
                    policyOptions.HttpRetry.Count,
                    retryAttempt => TimeSpan.FromSeconds(Math.Pow(policyOptions.HttpRetry.BackoffPower, retryAttempt))));
    
        policyRegistry.Add(
            PollyPolicyName.HttpCircuitBreaker,
            HttpPolicyExtensions
                .HandleTransientHttpError()
                .CircuitBreakerAsync(
                    handledEventsAllowedBeforeBreaking: policyOptions.HttpCircuitBreaker.ExceptionsAllowedBeforeBreaking,
                        durationOfBreak: policyOptions.HttpCircuitBreaker.DurationOfBreak));
    
        return services;
    }
    

提交回复
热议问题