0

I have IAsyncPolicy<HttpResponseMessage> which is a wrapper of 2 policies timeoutPolicy and waitAndRetryPolicy which I'm returning with a variable asyncPolicy.

Now I have another policy fallbackForCircuitBreaker which I want to wrap with asyncPolicy, but this gives me below error,

'IAsyncPolicy< HttpResponseMessage>' does not contain a definition for 'WrapAsync' and the best extension method overload 'IAsyncPolicyPolicyWrapExtensions.WrapAsync< HttpResponseMessage>(IAsyncPolicy, IAsyncPolicy)' requires a receiver of type 'IAsyncPolicy`

What this mean and how to resolve it?

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

        var fallbackForCircuitBreaker = Policy<bool>
                        .Handle<BrokenCircuitException>()
                        .OrInner<BrokenCircuitException>()
                        .Fallback(fallbackValue: false, onFallback: (b, context) => { Console.WriteLine("test"); });

        var X = asyncPolicy.WrapAsync<HttpResponseMessage>(fallbackForCircuitBreaker);

        Console.ReadKey();
    }

    public static IAsyncPolicy<HttpResponseMessage> CreateDefaultRetryPolicy()
    {
        var timeoutPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(180));

        var waitAndRetryPolicy = Polly.Policy
                .Handle<HttpRequestException>()
                .OrResult<HttpResponseMessage>(r => r.StatusCode == HttpStatusCode.InternalServerError)
                .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)),
                (result, timeSpan, context) =>{});

        return timeoutPolicy.WrapAsync(waitAndRetryPolicy);
    }
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
user584018
  • 10,186
  • 15
  • 74
  • 160

1 Answers1

0

When combining generic policies in a PolicyWrap, you can only wrap together policies for calls returning the same TResult type.

Your posted code is trying to wrap together a policy governing calls returning HttpResponseMessage, with a policy governing calls returning bool.

Put another way: You cannot transform the return type of the call mid PolicyWrap using FallbackPolicy.


If your goal is to capture both the outcome of the execution, and an overall status/boolean of whether it succeeded, see the .ExecuteAndCaptureAsync(...) syntax covered in the Polly readme here and here.

mountain traveller
  • 7,591
  • 33
  • 38