Warm tip: This article is reproduced from serverfault.com, please click

c#-在ASP.NET Core中使用reloadOnChange重新加载选项

(c# - Reloading Options with reloadOnChange in ASP.NET Core)

发布于 2018-06-29 08:28:50

在我的ASP.NET Core应用程序中,我将appsettings.json绑定到强类型的AppSettings

public Startup(IHostingEnvironment environment)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(environment.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<AppSettings>(Configuration);
    //...
}

在单例类中,我将这个AppSettings类包装如下:

public class AppSettingsWrapper : IAppSettingsWrapper
{
    private readonly IOptions<AppSettings> _options;

    public AppSettingsAdapter(IOptions<AppSettings> options)
    {
        _options = options ?? throw new ArgumentNullException("Options cannot be null");
    }

    public SomeObject SomeConvenienceGetter()
    {
        //...
    }
}

现在,如果json文件发生更改,我正在努力重新加载AppSettings。我在某处读到IOptionsMonitor可以检测到更改,但是在我的情况下它不起作用。

为了测试目的,我尝试像这样调用OnChange事件:

public void Configure(IApplicationBuilder applicationBuilder, IOptionsMonitor<AppSettings> optionsMonitor)
{
    applicationBuilder.UseStaticFiles();
    applicationBuilder.UseMvc();

    optionsMonitor.OnChange<AppSettings>(vals => 
    {
        System.Diagnostics.Debug.WriteLine(vals);
    });
}

当我更改json文件时,永远不会触发该事件。有人知道我可以进行哪些更改以使重装机制在我的方案中工作吗?

Questioner
Shamshiel
Viewed
0
Simply Ged 2018-06-29 18:51:37

你需要注入IOptionsSnapshot<AppSettings>以使重新加载工作。

很遗憾,你无法将加载IOptionsSnapshot到Singleton服务中。IOptionsSnapshot是范围服务,因此你只能在范围或瞬态注册类中引用它。

但是,如果考虑一下,那是有道理的。更改设置时需要重新加载设置,因此,如果将它们注入到Singleton中,则该类将永远不会获得更新的设置,因为不会为Singleton再次调用构造函数。