A good way to pass IConfiguration to static class?

385 Views Asked by At

I am using this dapper extension that uses polly for retry.

We can see that it defines a static retry policy:

private static readonly AsyncRetryPolicy RetryPolicy = 
    Policy
        .Handle<SqlException>(SqlServerTransientExceptionDetector.ShouldRetryOn)
        .Or<TimeoutException>()
        .OrInner<Win32Exception>(SqlServerTransientExceptionDetector.ShouldRetryOn)
        .WaitAndRetryAsync(RetryTimes,
            (exception, timeSpan, retryCount, context) =>
            {
                LogTo.Warning(
                    exception,
                    "WARNING: Error talking to ReportingDb, will retry after {RetryTimeSpan}. Retry attempt {RetryCount}",
                    timeSpan,
                    retryCount
                );
            });

Ideally I want to make RetryTimes a setting. However, I am not sure how can I pass IConfiguration to RetryTimes in a static property?

The work round I can think of is to define the polly policy as a Singleton (so I can read the setting). Then in this extension method, I actually pass the policy in. Is this about the right way to hanlde it in .NET Core?

1

There are 1 best solutions below

0
Gordon Khanh Ng. On

I think create a place to hold the setting and assign to it before you use would be fine.

// Create the holder class
public static class SettingHolder
{
    public static int RetryTimes = 0;
}

// Assign to it before you going to use it, in startup file would be nice.
public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            SettingHolder.RetryTimes = int.Parse(Configuration.GetSection("YourSection")["GoToYourSetting"]);
        }