首页 > 解决方案 > 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 中它是可用的。

标签: c#.net-core

解决方案


为了在配置对象上使用该Bind方法,您还需要Microsoft.Extensions.Configuration.BinderpackageMicrosoft.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");
});

如果您正在使用选项模式,您也可以为此使用选项监视器


推荐阅读