All Downloads are FREE. Search and download functionalities are using the official Maven repository.

csharp.libraries.generichost.IHttpClientBuilderExtensions.mustache Maven / Gradle / Ivy

There is a newer version: 7.7.0
Show newest version
{{>partial_header}}
{{#nrt}}
#nullable enable

{{/nrt}}
using System;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;{{#supportsRetry}}
using Polly.Timeout;
using Polly.Extensions.Http;
using Polly;{{/supportsRetry}}

namespace {{packageName}}.Extensions
{
    /// 
    /// Extension methods for IHttpClientBuilder
    /// 
    {{>visibility}} static class IHttpClientBuilderExtensions
    {
        {{#supportsRetry}}
        /// 
        /// Adds a Polly retry policy to your clients.
        /// 
        /// 
        /// 
        /// 
        public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries)
        {
            client.AddPolicyHandler(RetryPolicy(retries));

            return client;
        }

        /// 
        /// Adds a Polly timeout policy to your clients.
        /// 
        /// 
        /// 
        /// 
        public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout)
        {
            client.AddPolicyHandler(TimeoutPolicy(timeout));

            return client;
        }

        /// 
        /// Adds a Polly circuit breaker to your clients.
        /// 
        /// 
        /// 
        /// 
        /// 
        public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak)
        {
            client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak));

            return client;
        }

        private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries)
            => HttpPolicyExtensions
                .HandleTransientHttpError()
                .Or()
                .RetryAsync(retries);

        private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout)
            => Policy.TimeoutAsync(timeout);

        private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy(
            PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak)
                => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak);
        {{/supportsRetry}}
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy