【发布时间】:2018-12-08 09:27:55
【问题描述】:
在我的 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 文件时,该事件永远不会触发。有人知道我可以改变什么来让重新加载机制在我的场景中工作吗?
【问题讨论】:
-
这感觉像是一个错误。如果您要添加 json 文件并希望在更改时重新加载调用,那么将更改保存到文件应调用任何更改处理程序并将 haschanged 设置为 true。
标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.0 asp.net-core-webapi