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

时间:2019-11-15 15:52:28

标签: c# .net-core configuration reload

我试图设置一个控制台应用程序以重新加载“ 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 彼得

1 个答案:

答案 0 :(得分:1)

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

中使用扩展方法。

密钥在OptionsConfigurationServiceCollectionExtensions类和OptionsMonitor类中。 您可以在OptionsMonitor类的构造函数中看到,它将采用在Service容器中注册的所有IOptionsChangeTokenSource实例,这些实例是由OptionsConfigurationServiceCollectionExtensions.Configure方法注册的。IOptionsChangeTokenSource实例在更改配置不足的文件时重新加载选项。

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