【发布时间】:2020-12-07 16:15:12
【问题描述】:
要配置我的服务,我需要按实例设置单例,如下所示:
IConfigurationSection settingsSection = Configuration.GetSection("AppSettings");
MySettings settings = new MySettings();
settingsSection.Bind(settings);
// something to do with the instance, so I need it here
services.Configure<MySettings>(settings);
当我检查 settingsSection 项目时,我看到它的键都以 Appsettings: 为前缀(即:AppSettings:AppId、AppSettings:AppUrl、...)。
因此,绑定未完成,我的 settings 对象未初始化。
有没有办法阻止这个前缀,因为我已经知道我在那个部分?
下面是 appsettings.json 的样子:
{
"AppSettings": {
"AppId": 3540350,
"AppUrl": "http://localhost:542",
"AppEnabled": true,
...
}
}
MySettings 类如下所示:
public class MySettings
{
public int AppId { get; set;}
public string AppUrl { get; set;}
public bool AppEnabled { get; set;}
...
}
编辑
我愚蠢地保留了一个无法反序列化的旧命名约定(我猜):
{
"AppSettings": {
"App.Id": 3540350,
"App.Url": "http://localhost:542",
"App.Enabled": true,
...
}
}
这个问题可以结束了。
【问题讨论】:
-
有一个扩展方法可以接收该部分并配置
IOptions,因此您只需执行services.Configure<MySettings>(Configuration.GetSection("AppSettings"))之类的操作 -
@dcg "我需要按实例设置单例"
标签: c# dependency-injection configuration