【问题标题】:A good way to pass IConfiguration to static class?将 IConfiguration 传递给静态类的好方法?
【发布时间】:2021-08-17 21:26:26
【问题描述】:

我正在使用这个 dapper extension,它使用 polly 进行重试。

我们可以看到它定义了一个静态重试策略:

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

理想情况下,我想设置RetryTimes。但是,我不确定如何在静态属性中将IConfiguration 传递给RetryTimes

我能想到的工作是将 polly 策略定义为 Singleton(这样我就可以读取设置)。然后在这个扩展方法中,我实际上传递了策略。这是关于在 .NET Core 中处理它的正确方法吗?

【问题讨论】:

  • 在已经获得配置访问权限后,在启动期间设置静态策略。
  • 您如何在代码中使用该策略?如果您在从 DI 解析的类中使用 RetryPolicy,您还可以将重试策略解析为来自 DI 的单例。

标签: c# asp.net-core retrypolicy


【解决方案1】:

我认为创建一个地方来保存设置并在使用之前分配给它会很好。

// 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"]);
        }

【讨论】:

    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    相关资源
    最近更新 更多