I'm looking for inputs and hopefully some sample implementation to use Polly with EF Core 3.1. My AspNetCore application uses Azure SQL with EF and repository pattern. I want to use Polly with RetryAndWait policy for Azure SQL requests beginning with initial connection. I have read that EF Core 3.1 supports EnableRetryOnFailure execution strategy on DbContext. However, I want to see if I can use Polly instead to be consistent with other areas of my application like webApi calls. May be hook Polly within custom execution strategy of EF.
Here is my sample implementation of repository where i want to use Polly policies:
public interface IGenericRepository<T> : IDisposable
{
Task<IReadOnlyList<T>> ListAllAsync(CancellationToken cancellationToken = default);
Task<T> GetByIdAsync(CancellationToken cancellationToken = default, int id);
}
public class EfSqlGenericRepository<T> : IGenericRepository<T>
{
private readonly DbContext _dbContext;
public EfSqlGenericRepository(DbContext dbContext)
{
this._dbContext = dbContext;
}
public async Task<T> GetByIdAsync(
CancellationToken cancellationToken = default, int id)
{
// retrieve entity via dbcontext
}
public async Task<IReadOnlyList<T>> ListAllAsync(CancellationToken cancellationToken = default)
{
// list entities via dbcontext
}
}
public class DapperRepository<T> : IGenericRepository<T>
{
private readonly string _cxn;
public DapperRepository(string cxn)
{
this._cxn = cxn;
}
public async Task<T> GetByIdAsync(
CancellationToken cancellationToken = default, int id)
{
// retrieve entity via IDbConnection & sql query
}
public async Task<IReadOnlyList<T>> ListAllAsync(CancellationToken cancellationToken = default)
{
// list entities via IDbConnection & sql query
}
}
So in terms of application requirements:
When a SQL (or other known) transient error happens, I need to retry for maximum 6 times but with every attempt I need to wait exponentially before trying it again. And if the error persists even after 6th attempt, I want to break the circuit for the next 25 seconds. Finally, if the failure still exists, degrade gracefully using a fallback.