在ASP.NET Core中使用reloadOnChange重新加载选项 [英] Reloading Options with reloadOnChange in ASP.NET Core
问题描述
在我的ASP.NET Core应用程序中,我将appsettings.json绑定到强类型的类 AppSettings .
In my ASP.NET Core application I bind the appsettings.json to a strongly typed class 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类包装为:
In a singleton class I wrap this AppSettings class like this:
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 可以检测到更改,但不适用于我的情况.
Now I'm struggling with reloading the AppSettings if the json file changes. I read somewhere that the class IOptionsMonitor can detect changes but it doesn't work in my case.
出于测试目的,我尝试像这样调用 OnChange 事件:
I tried calling the OnChange event like this for testing purposes:
public void Configure(IApplicationBuilder applicationBuilder, IOptionsMonitor<AppSettings> optionsMonitor)
{
applicationBuilder.UseStaticFiles();
applicationBuilder.UseMvc();
optionsMonitor.OnChange<AppSettings>(vals =>
{
System.Diagnostics.Debug.WriteLine(vals);
});
}
当我更改json文件时,永远不会触发该事件.有人知道我可以进行哪些更改以使重装机制在我的场景中正常工作吗?
The event is never triggered when I change the json file. Has someone an idea what I can change to get the reloading mechanic to work in my scenario?
推荐答案
您需要注入IOptionsSnapshot<AppSettings>
才能使重新加载正常工作.
You need to inject IOptionsSnapshot<AppSettings>
to get the reload working.
很遗憾,您无法将IOptionsSnapshot
加载到Singleton服务中. IOptionsSnapshot
是范围服务,因此您只能在范围或瞬态注册的类中引用它.
Unfortunately you cannot load the IOptionsSnapshot
into a Singleton service. IOptionsSnapshot
is a Scoped service so you can only reference it in a Scoped or Transient registered class.
但是,如果考虑一下,那是有道理的.更改设置时需要重新加载设置,因此,如果将它们注入到Singleton中,则该类将永远不会获得更新的设置,因为不会为Singleton再次调用构造函数.
But, if think about it, that makes sense. The settings need to be reloaded when they change so if you inject them into a Singleton then the class will never get the updated settings because the constructor will not be called again for a Singleton.
这篇关于在ASP.NET Core中使用reloadOnChange重新加载选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!