0

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);
    }
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
user584018
  • 10,186
  • 15
  • 74
  • 160

1 Answers1

1

.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>();
mountain traveller
  • 7,591
  • 33
  • 38
  • Thanks a lot. You keep helping me since few days. Would you mind my this question, if you have any thoughts? https://stackoverflow.com/questions/58928939/how-to-implement-custom-method-when-polly-circuit-is-close – user584018 Nov 20 '19 at 03:29