c# - 无法使用 IOptionsMonitor 检测 ASP.NET Core 中的更改

标签 c# asp.net-core

我正在开发 Asp.Net Core 应用

我想在运行应用程序后更改配置设置

我正在使用 IOptionsMonitor,但它没有检测到变化

在 Startup.cs -> Configuration() 方法中我有

services.Configure<Config>(Configuration.GetSection("someConfig"));

在读取这些配置设置的不同类中,我写了类似的东西

var someConfig= serviceProvider.GetRequiredService<IOptionsMonitor<Config>>();

但是当我更改配置文件(Json File)时,没有检测到更改,并且someConfig没有更改。

配置 POCO 类:

public class Config
{
    public string name {get; set;}
    //More getters and setters
}

编辑:

services.AddSingleton<ConfigHelpers>;

我正在使用一个单例对象,我试图在其中读取配置。如果它不是 snigleton,它工作正常。有没有办法在单例对象中更改配置?

在 ConfigHelpers.cs 中

var someConfig= serviceProvider.GetRequiredService<IOptionsMonitor<Config>();

由于在 Startup.cs 中定义为单例,所以对 Config 所做的更改不会反射(reflect)出来。

最佳答案

您是否像这样创建了您的WebHostBuilder aprox:

var config = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("config.json", optional: false, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();

var AppConfig = config.Get<AppConfig>();

var host = new WebHostBuilder()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("http://*:" + (AppConfig.Port ?? 80))
    .UseKestrel()
    .UseIISIntegration()
    // Clones your config values
    .UseConfiguration(config)
    .UseStartup<Startup>()
    .Build();

然后它将克隆您的值,您将失去实时重新加载能力。

您必须使用 ConfigureAppConfiguration 并执行以下操作:

var host = new WebHostBuilder()
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseUrls("http://*:" + (AppConfig.Port ?? 80))
    .UseKestrel()
    .ConfigureAppConfiguration((builder, conf) =>
    {
        conf.SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("config.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
    })
    .UseIISIntegration()
    //.UseConfiguration(config)
    .UseStartup<Startup>()
    .Build();

关于c# - 无法使用 IOptionsMonitor 检测 ASP.NET Core 中的更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49454153/

相关文章:

c# - 如何从资源项目中获取图像

visual-studio-2013 - 如何将 ASP.NET 5 模板添加到 Visual Studio 2013 Update 5?

c# - 在 web api 中使用 async await 的最佳实践

c# - 使用参数 AutoMapper 映射 View 模型子级

c# - Controller 方法不会从重定向中捕获对象路由

c# - 如何隐藏XNA 4.0?

c# - C# 如何评估数组循环 boolean 相等性?

c# - 上传文件 ASP.NET 5

c# - 打开 GPIO 引脚时无法打开设备句柄

c# - 无法从父类转换为子类