IOptionsSnapshot在.Net Core 2控制台应用程序中不起作用

时间:2018-10-05 16:24:25

标签: .net-core

我想使用IOptionsSnapshot帮助更改时重新加载文件, 我试过了IOptionsSnapshot可以在ASP.NET Core中工作, 但是在.NET Core控制台中更改文件时重新加载文件时,它无法更改设置,以下是我的测试代码:

class Program
{
    static IConfiguration Configuration { get; set; }
    static ServiceProvider ServiceProvider { get; set; }
    static void Main(string[] args)
    {
        Configuration
            = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .Build();

        ServiceProvider = new ServiceCollection()
             .AddScoped<MyService>()
             .Configure<MySetting>(Configuration.GetSection("mysection"))
             .BuildServiceProvider();


        while (true)
        {
            Task.Run(() =>
            {
                using (var scope = ServiceProvider.CreateScope())
                {
                    var service = scope.ServiceProvider.GetRequiredService<MyService>();

                }
            });

            var key = Console.ReadKey();
            if (key.Key == ConsoleKey.Q)
                return;
        }
    }
}


public class MySetting
{
    public string Name { get; set; }
}

public class MyService
{
    private readonly MySetting _mySetting;

    public MyService(IOptionsSnapshot<MySetting> mySettingAccessor)
    {
        _mySetting = mySettingAccessor.Value;
        Console.WriteLine(_mySetting.Name);
    }
}

和我的appsettings.json内容:

{
  "mysection": {
    "Name": "MyName"
  }
}

感谢您的帮助。

0 个答案:

没有答案