如何在dotnet core 3控制台应用程序中进行更改后重新加载'appsettings.json'

问题描述 投票:0回答:1

我正在尝试设置一个控制台应用程序以重新加载'appsettings.json',但我无法让它对文件的更改做出反应。

我已经这样设置了主体:

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彼得

c# .net-core configuration reload
1个回答
0
投票

您不能使用扩展方法AddOptions来执行此操作,因为它不适用于文件配置提供程序。为此,必须在类OptionsConfigurationServiceCollectionExtensions

中使用扩展方法

键位于OptionsConfigurationServiceCollectionExtensions类和OptionsMonitor类中。您可以在OptionsMonitor类的构造函数中看到,它将采用在Service容器中注册的所有IOptionsChangeTokenSource实例,这些实例是由OptionsConfigurationServiceCollectionExtensions.Configure方法注册的。

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

© www.soinside.com 2019 - 2024. All rights reserved.