c# - Json 文件 - 更改跟踪和重新加载
问题描述
我有一个 .NET Core 2.0 控制台应用程序,它有一个 AppConfiguration 文件,它提供不同的应用程序设置。我在主方法中添加了一个ConfigurationBuilder
对象的创建,并reloadOnChange
为该 JSON 文件添加了标志,如下面的代码所示。
static void Main(string[] args)
{
Console.WriteLine("Program started...");
Console.WriteLine("Stop Program by Ctrl+C");
//Add Exit Possibility
Console.CancelKeyPress += CurrentDomain_ProcessExit;
//Add Configuration Builder
Console.Write("Load Shared Configuration...");
Configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("SharedAppConfiguration.json", optional: false, reloadOnChange: true)
.Build();
Console.WriteLine("done");
}
如何捕获或获取有关 JSON 文件“SharedAppConfiguration.json”已更改的事件的信息?
我试图做这样的事情:
Configuration.GetSection("AppConfiguration").Bind(appConfiguration);
但看起来,.Bind
.NET Core 控制台应用程序中没有方法 - 在 ASP.NET 中它是可用的。
解决方案
为了在配置对象上使用该Bind
方法,您还需要Microsoft.Extensions.Configuration.Binder
package。Microsoft.Extensions.Configuration
仅附带用于配置的基本内容,并且Microsoft.Extensions.Configuration.Json
只是 JSON 文件的加载器。
要回答您的其他问题,关于如何通过 获取有关 JSON 配置文件的配置更改的通知reloadOnChange: true
,您可以为此使用重新加载更改令牌。为此使用ChangeToken.OnChange
辅助函数是最简单的:
var configuration = new ConfigurationBuilder()
.AddJsonFile("file.json", optional: false, reloadOnChange: true)
.Build();
// register change callback
ChangeToken.OnChange(() => configuration.GetReloadToken(), () => {
Console.WriteLine("Configuration changed");
});
推荐阅读
- php - 动态 HTML 类 PHP 和 WordPress
- javascript - 复制到 clibboard + 之前有一些文本
- python - 运行命令行参数时Python cv2导入错误
- django - 尝试在 docker 容器中使用 PostgreSQL db 运行 Unittest 时出错
- performance - 如何检测 pytorch 中的所有 GPU/CPU 传输?
- authentication - 用于身份验证的 NetCore 3.1 Blazor WASAM 客户端 x509 证书
- bootstrap-4 - 引导表单选择及其验证的问题
- lua - Lua C - 有没有办法在 C 中保留一个值,但仍然没有垃圾收集?
- python - 实现回调 Tkinter
- python - 在 python 中打印时出现“TypeError:字符串索引必须是整数”;数量和单位列表字典