getting conversion error while trying to wrap 2 Polly policies

2k views Asked by At

I am trying to wrap two Polly policies and want to return IAsyncPolicy, but it giving error,

convert from Polly.Retry.RetryPolicy < System.Net.Http.HttpResponseMessage> to Polly.IAsyncPolicy

public static IAsyncPolicy 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 Policy.WrapAsync(timeoutPolicy, waitAndRetryPolicy);
    }

How to wrap this and return?

1

There are 1 answers

0
mountain traveller On BEST ANSWER

Adapt your code as follows:

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);
}

Explanation

  • The timeout policy is non-generic, IAsyncPolicy.
  • The wait-and-retry policy is generic, IAsyncPolicy<HttpResponseMessage>, as it handles HttpResponseMessage results.

To combined these in a PolicyWrap, use the .Wrap(...) instance-method syntax:

return timeoutPolicy.WrapAsync(waitAndRetryPolicy);

As the resulting PolicyWrap handles HttpResponseMessage, it is also of type IAsyncPolicy<HttpResponseMessage>, so the method return type changes to that.

Polly documentation covers the differences between non-generic and generic policies in the wiki.