Json 文件 - 更改跟踪和重新加载 [英] Json File - Changed Tracking and Reload

查看:28
本文介绍了Json 文件 - 更改跟踪和重新加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .NET Core 2.0 控制台应用程序,它有一个提供不同应用程序设置的 AppConfiguration 文件.我在主方法中添加了 ConfigurationBuilder 对象的创建,并为该 JSON 文件添加了 reloadOnChange 标志,如下面的代码所示.

I have a .NET Core 2.0 console application which has a AppConfiguration file which provides different app-settings. I have added in the main-method the creation of a ConfigurationBuilder object and added the reloadOnChange flag for that JSON file like in the code below.

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"已更改?

How can I catch or get information about the event, that the JSON file "SharedAppConfiguration.json" has changed?

我曾尝试做这样的事情:

I've tried to do something like this:

Configuration.GetSection("AppConfiguration").Bind(appConfiguration);

但看起来,.NET Core 控制台应用程序中没有 .Bind 方法 - 在 ASP.NET 中它是可用的.

But like it looks, there is no .Bind method in .NET Core console application - in ASP.NET it’s available.

推荐答案

为了使用 Bind 方法在配置对象上,你还需要Microsoft.Extensions.Configuration.Binder.Microsoft.Extensions.Configuration 仅附带用于配置的基本内容,而 Microsoft.Extensions.Configuration.Json 只是 JSON 文件的加载器.

In order to use the Bind method on the configuration objects, you also need the Microsoft.Extensions.Configuration.Binder package. Microsoft.Extensions.Configuration only comes with the base stuff to work with the configuration, and Microsoft.Extensions.Configuration.Json is only the loader for JSON files.

要回答您的另一个问题,即如何使用 reloadOnChange: true 获取有关 JSON 配置文件的配置更改的通知,您可以为此使用重新加载更改令牌.使用 ChangeToken.OnChange 辅助函数:

To answer your other question, about how to get notified about configuration changes for JSON configuration files with reloadOnChange: true, you can use the reload change token for this. It’s easiest to use the ChangeToken.OnChange helper function for that:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("file.json", optional: false, reloadOnChange: true)
    .Build();

// register change callback
ChangeToken.OnChange(() => configuration.GetReloadToken(), () => {
    Console.WriteLine("Configuration changed");
});

如果您使用的是 选项模式,您还可以使用选项监控为此.

If you are using the options pattern, you can also use the options monitor for this.

这篇关于Json 文件 - 更改跟踪和重新加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆