is anyone able to tell me why this is not working?
I am attempting to make a generic Interface to define a Polly RetryPolicy and CircuitBreaker policy in c# but am getting a compilation error:
CS0029: Cannot Implicitly Convert Type 'Polly.Retry.AsyncRetryPolicy' to 'T'
Type AsyncRetryPolicy derives from IAsyncPolicy so I do not know why this is not working.
public interface IPollyPolicy<T> where T : IAsyncPolicy
{
T PolicyAsync { get; }
Task ExecuteAsync(Func<Task> operation, CancellationToken cancellationToken);
Task<TResult> ExecuteAsync<TResult>(Func<Task<TResult>> operation, CancellationToken cancellationToken);
}
public class MyRetryPolicy<T> : IPollyPolicy<T> where T : IAsyncPolicy
{
public T PolicyAsync { get; }
public MyRetryPolicy(int retryCount = 3, int initialWaitMs = 3000, double factor = 3, bool fastFirst = true)
{
var delay = Backoff.ExponentialBackoff(TimeSpan.FromMilliseconds(initialWaitMs), retryCount: retryCount,
factor: factor, fastFirst: fastFirst).ToList();
// this line Throws the error:
PolicyAsync = Policy
.Handle<SqlException>()
.WaitAndRetryAsync(delay);
}
public class MyCircuitBreakerPolicy<T> : IPollyPolicy<T> where T : IAsyncPolicy
{
public T PolicyAsync { get; }
public MyCircuitBreakerPolicy(int retryCount = 3, int initialWaitMs = 3000, double factor = 3, bool fastFirst = true)
{
PolicyAsync = Policy
.Handle<SqlException>()
.CircuitBreakerAsync(exceptionsAllowedBeforeBreaking: exceptionsAllowedBeforeBreaking,
durationOfBreak: TimeSpan.FromSeconds(durationofBreakSeconds));
}
then to consume these, using a factory :
public class PolicyFactory : IPolicyFactory
{
public IAsyncPolicy GetAsync(PolicyType policyType)
{
switch (policyType)
{
case PolicyType.RetryPolicy:
return new MyRetryPolicy(3, 3000, 3, true);
case PolicyType.CircuitBreakerPolicy:
return new MyCircuitBreakerPolicy(2, 5);
}
}
}
Any help Would be much appreciated !
Thanks Andrew.