Created by: jeffshantz
Summary
Use Policy<IRestResponse>
and AsyncPolicy<IRestResponse>
instead of RetryPolicy<IRestResponse>
and AsyncRetryPolicy<IRestResponse>
to allow for use of wrapped policies.
Background
In the .NET Core client generator, RetryConfiguration
uses the type RetryPolicy<IRestResponse>
and AsyncRetryPolicy<IRestResponse>
for its properties RetryPolicy
and AsyncRetryPolicy
, respectively.
This is useful, as it allows one to define a retry policy:
RetryConfiguration.RetryPolicy =
Policy
.HandleResult<IRestResponse>(r => r.StatusCode == HttpStatusCode.Unauthorized)
.Retry(retryCount: 3,
onRetry: ((result, retryNumber, context) =>
{
// Fetch new API token here
Console.WriteLine("Retrying...");
}));
The problem is that this does not allow us to exploit the full utility of Polly. For instance, after retrying 3 times, I might want to log a message or perform some action before giving up. In this case, it would be nice to use Policy.Wrap()
:
var retryPolicy =
Policy
.HandleResult<IRestResponse>(r => r.StatusCode == HttpStatusCode.Unauthorized)
.Retry(retryCount: 3,
onRetry: ((result, retryNumber, context) =>
{
// Fetch new API token here
Console.WriteLine("Retrying...");
}));
var giveUpPolicy =
Policy
.HandleResult<IRestResponse>(r => true)
.Fallback(fallbackValue: null, onFallback: result =>
{
Console.WriteLine("Giving up");
});
RetryConfiguration.RetryPolicy = giveUpPolicy.Wrap(retryPolicy);
Solution
This pull request simply changes the type of the RetryPolicy
and AsyncRetryPolicy
properties to their higher-level base classes in RetryConfiguration
such that:
/// <summary>
/// Retry policy
/// </summary>
public static RetryPolicy<IRestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncRetryPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
becomes:
/// <summary>
/// Retry policy
/// </summary>
public static Policy<IRestResponse> RetryPolicy { get; set; }
/// <summary>
/// Async retry policy
/// </summary>
public static AsyncPolicy<IRestResponse> AsyncRetryPolicy { get; set; }
Then, one can still assign a RetryPolicy
as usual, but one can now also use wrapped policies, as above. No other changes are required -- this worked out of the box when I made these type changes.