[英]Reloading appsettings.json using Strongly type
This is my appsettings.json
这是我的appsettings.json
{
"MySettings": {
"DefaultSetting": "Key1",
"Settings": {
"Key1": {
"Full": "Description1",
"Short": "Desc1"
},
"Key2": {
"Full": "Description2",
"Short": "Desc2"
},
"Key3": {
"Full": "Description3",
"Short": "Desc3"
}
}
}
}
My Class defined:我的班级定义:
public class MySettings
{
public Dictionary<string, Setting> Settings { get; set; }
public string DefaultSetting { get; set; }
}
public class Setting
{
public string Full { get; set; }
public string Short { get; set; }
}
My Startup.cs
:我的Startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<MySettings>(Configuration.GetSection("MySettings"));
services.AddMvc();
}
In HomeController:在家庭控制器中:
public class HomeController : Controller
{
private readonly MySettings _mySettings;
public HomeController(IOptionsSnapshot<MySettings> mySettings)
{
this._mySettings= mySettings.Value;
}
public IActionResult Index()
{
return Json(_mySettings.DefaultSetting);
}
}
I want to get the new setting values when I save the changed appsettings.json
file and refresh my browser.我想在保存更改后的appsettings.json
文件并刷新浏览器时获取新的设置值。
I have tried the IOptionsMonitor
before我之前尝试过IOptionsMonitor
But I have many strongly typed classes, it will register too many IOptionsMonitor
.但是我有很多强类型类,它会注册太多IOptionsMonitor
。
Is there an easier way to implement auto reload strongly typed class?有没有更简单的方法来实现自动重载强类型类?
Yes, you can reload appsettings on change.是的,您可以在更改时重新加载应用程序设置。 To do this, in startup constructor, assign reloadOnChange to true like this-为此,在启动构造函数中,像这样将reloadOnChange分配给 true -
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.