.NET Core控制台应用程序中的IOptionsSnapshot无法正常工作

时间:2018-08-22 14:48:33

标签: dependency-injection .net-core

下面是.NET Core控制台应用程序的示例,它与IOptionsSnapshot<T>一起使用构造函数依赖项注入。

class Program
{
    static void Main(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", 
                optional: false, reloadOnChange: true)
            .Build();

        IServiceProvider provider = new ServiceCollection()
            .Configure<AppSettings>(
                configuration.GetSection("AppSettings"))
            .AddTransient<CheckOption>()
            .BuildServiceProvider();

        while (true)
        {
            if (Console.ReadLine() != "stop")
            {
                CheckOption checkOption = 
                    provider.GetRequiredService<CheckOption>();

                checkOption.Run();
            }
            else
            {
                return;
            }
        }
    }
}
public class CheckOption
{
    public AppSettings _AppSettings;     

    public CheckOption(IOptionsSnapshot<AppSettings> appSettings)
    {
        _AppSettings = appSettings.Value;
    }

    public void Run()
    {            
      string option1 = _AppSettings.Option1;
      string option2 = _AppSettings.Option2;
    }
}

public class AppSettings
{
    public string Option1 {get; set;}
    public string Option2 {get; set;}
}

在while循环中更改“ appsettings.json”后,Option1Option2的值保持不变。

0 个答案:

没有答案