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

查看:354
本文介绍了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?

我尝试执行以下操作:

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

但是看起来好像没有 .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

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通知有关JSON配置文件的配置更改的问题:true ,您可以为此使用重新加载更改令牌。使用 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天全站免登陆