asp.net-core - 具有动态(运行时)值的选项配置
问题描述
我有一个 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).
对我有什么建议吗?
解决方案
您可以尝试注册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);
}
推荐阅读
- reactjs - MongoDB - 如何在数组中更新或插入对象
- reactjs - React Hook 表单 - 添加动态字段行
- apache-flink - 在 Flink 中从不调用 notifyCheckpointComplete
- bitmap - 在 MIPS 中绘制圆以位图显示
- python - 如何在 Python 中打印多个字符串中的多个变量
- javascript - ValueError:视图未返回 HttpResponse 对象。它返回 None 。(Django/ImgKit)
- c - C中的整数算术溢出预防
- android - Firebase 身份验证:在身份验证期间没有收到来自 FirebaseUser 的电子邮件
- html - 从 Vue 调用 laravel 路由
- c# - 如何按部分将 JSON 文件反序列化为 C# 对象