gpt4 book ai didi

c# - 如何在更改 dotnet core 3 控制台应用程序时重新加载 'appsettings.json'

转载 作者:行者123 更新时间:2023-12-04 17:31:52 24 4
gpt4 key购买 nike

我正在尝试设置一个控制台应用程序来重新加载“appsettings.json”,但我无法让它对文件的更改使用react。

我已经像这样设置了主要的:

private static void Main ()
{
configuration = LoadConfiguration ();

var services = ConfigureServices ();

var serviceProvider = services.BuildServiceProvider ();

serviceProvider.GetService<ConsoleApp> ().Run ();
}

private static IConfiguration LoadConfiguration ()
=> new ConfigurationBuilder ().SetBasePath (GetApplicationDirectory ())
.AddJsonFile (_APP_SETTING_FILE_NAME, optional: false, reloadOnChange: true)
.Build ();

private static IServiceCollection ConfigureServices ()
{
IServiceCollection services = new ServiceCollection ();

configuration.Bind (new AppSettings ()); // binds the 'appsettings.json' to the class

services.AddSingleton (configuration);
services.AddTransient<ConsoleApp> ();

services.AddOptions<AppSettings> (); // adds the IOption<T> and IOptionMonitor<T>

// here I'm trying to follow a post from Dino Esposito [https://www.red-gate.com/simple-talk/dotnet/net-development/asp-net-core-3-0-configuration-factsheet/][1] but services.Configure<AppSettings>() does not compile
// the failure could be here? :-(
services.Configure<AppSettings> (opt => opt.Default = configuration["Default"]);

return services;
}

我很确定我在 DI 的配置中做错了什么,但我不知道是什么。

控制台应用程序非常简单,应该注册 cahgne 但没有注册,反正就在这里

public class ConsoleApp
{
public AppSettings AppSettings { get; }

public ConsoleApp (IOptionsMonitor<AppSettings> appSettingsOptionsMonitor)
{
AppSettings = appSettingsOptionsMonitor.CurrentValue;

appSettingsOptionsMonitor.OnChange ((arg1, arg2) => Console.WriteLine ($"\t ---> AppSettings changed to '{arg1.Default}' - '{arg2}'"));

Console.WriteLine ($"ctor - appsettings current value: '{AppSettings.Default}'.\n");
}

public void Run ()
{
Console.WriteLine ($"\tCurrent value: '{AppSettings.Default}' - waiting for change ...");

while (AppSettings.Default != "Stop") { }

Console.WriteLine ($"\t... has changed to '{AppSettings.Default}'.");
}
}

AppSettings 类是:

public class AppSettings
{
public string Default { get; set; }
}

如有任何帮助,我们将不胜感激!

T'X彼得

最佳答案

不能使用扩展方法AddOptions去做这个,因为它不是为与文件配置提供程序一起工作而设计的。为此,您必须使用 OptionsConfigurationServiceCollectionExtensions 类中的扩展方法。

关键在OptionsConfigurationServiceCollectionExtensions类和 OptionsMonitor类(class)。您可以在 OptionsMonitor 类的构造函数中看到,它会获取服务容器中注册的所有 IOptionsChangeTokenSource 实例,这些实例是通过 OptionsConfigurationServiceCollectionExtensions.Configure 方法注册的。IOptionsChangeTokenSource 实例会在配置文件更改时重新加载选项。

作为比较,您可以在 AddOptions 中看到方法,它不会注册 IOptionsChangeTokenSource 实例。

关于c# - 如何在更改 dotnet core 3 控制台应用程序时重新加载 'appsettings.json',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58880525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com