Search code examples
c#pollycircuit-breakerretry-logicpolicywrap

how to capture CircuitState for AsyncCircuitBreakerPolicy


I have a variable asyncPolicy of type IAsyncPolicy which has one or more policy including AsyncCircuitBreakerPolicy. Now I want to get specific policy say AsyncCircuitBreakerPolicy before a API call, so that I can extract the status of Circuit.

Is this possible? then how? Below code gives error, 'IAsyncPolicy' does not contain a definition for 'GetPolicy'

static void Main(string[] args)
    {
        var asyncPolicy = CreateDefaultRetryPolicy();

        var breaker = asyncPolicy.GetPolicy<AsyncCircuitBreakerPolicy>();
        var state = breaker.CircuitState;

        //Web API call follows with asyncPolicy

        Console.ReadKey();
    }

    public static IAsyncPolicy CreateDefaultRetryPolicy()
    {
        var retryPolicy = Policy.Handle<BrokenCircuitException>().WaitAndRetryAsync
            (
                retryCount: 3,
                sleepDurationProvider: attempt => TimeSpan.FromSeconds(Math.Pow(2, attempt))
            );

        var circuitBreaker = Policy.Handle<HttpRequestException>().CircuitBreakerAsync(
        exceptionsAllowedBeforeBreaking: 3,
        durationOfBreak: TimeSpan.FromSeconds(5000),
        onBreak: (exception, timespan, context) => { },
        onReset: (context) => { });

        return Policy.WrapAsync(retryPolicy, circuitBreaker);
    }

Solution

  • .GetPolicy<T>() is only for PolicyWraps. Technically, it is an extension method on IPolicyWrap.

    You could change the return type of CreateDefaultRetryPolicy() to be AsyncPolicyWrap

    public static AsyncPolicyWrap CreateDefaultRetryPolicy()
    

    Or you could cast where you call .GetPolicy<T>()

    var breaker = ((IPolicyWrap)asyncPolicy).GetPolicy<AsyncCircuitBreakerPolicy>();