首页 > 解决方案 > 具有动态(运行时)值的选项配置

问题描述

我有一个 MySettings 类,我想将其配置为 Options 以通过依赖注入使其可用。

目前我这样做(在服务构建器扩展方法中):

services.Configure<MySettings>(configuration.GetSection(MySettings.CustomSectionName));

我的问题是一部分设置来自 appsettings,而其他值仅在运行时(启动)时才知道。

因此,我尝试找出如何通过添加运行时提供的值来配置设置。我试图将值添加到配置中

configuration["SectionName:ValueX"] = "my runtime value";

That did not work and ValueX is always null (when the options are injected in the controller).

对我有什么建议吗?

标签: asp.net-core.net-coreasp.net-core-mvc

解决方案


您可以尝试注册MySettings而不是IOptions<MySettings>喜欢

public void ConfigureServices(IServiceCollection services)
{          
    var mySettings = new MySettings();
    Configuration.Bind("MySettings", mySettings);
    mySettings.Title = "Hello";
    services.AddSingleton(mySettings);
}

并使用MySettings喜欢

public class HomeController : Controller
{
    private readonly MySettings _settings;
    public HomeController(MySettings settings)
    {
        _settings = settings;
    }
    public IActionResult Index()
    {
        return Ok(_settings);
    }

推荐阅读