我有以下appSettings.json文件:
"SundrySettings": {
"CookieName": "Cookie",
"AccessGroup": "Software Development",
"Terminals" : {
"Raucherplatz" : "tablet1.local",
"Service" : "tablet2.local",
"Technik" : "tablet3.local",
"Technik" : "tablet4.local",
"Container" : "tablet5.local"
}
}
}
我想加载到以下结构中:
public class Terminal
{
public string Name;
public string Description;
}
public class SundryOptions
{
public string CookieName { get; set; } = "dummy";
public string HRAccessGroup { get; set; } = "dummy";
public List<Terminal> Terminals;
}
我将尝试使用以下命令加载:
ServiceProvider sp = services.BuildServiceProvider();
SundryOptions sundryOptions = sp.GetService<IOptions<SundryOptions>>().Value;
我遇到的问题是,使用属性初始化程序永远不会正确设置终端列表。我确实需要一个列表(而不是字典),因为实体可能是双重的,即在我的示例中为Technik。
我假设我在Class中有一些错误->对于任何指针我都会很高兴。
答案 0 :(得分:1)
按如下所示进行适当的配置处理:
var cookieName =
Configuration.GetSection("SundrySettings:CookieName").Value;
var accessGroup = Configuration.GetSection("SundrySettings:AccessGroup").Value;
var terminals = new List<Terminal>()
var terminalSections = this.Configuration.GetSection("Terminals").GetChildren();
foreach (var item in terminalSections)
{
terminals.Add(new Terminal
{
// perform type mapping here
});
}
SundryOptions sundryOption = new SundryOptions()
{
CookieName = cookieName,
HRAccessGroup = accessGroup,
Terminals = terminalList
};
当然可以有较短的版本,但是您可以从这里开始。
答案 1 :(得分:0)
执行以下操作:
var cookieName = Configuration.GetSection("SundrySettings:CookieName").Value;
var accessGroup = Configuration.GetSection("SundrySettings:AccessGroup").Value;
var terminals = Configuration.GetSection("SundrySettings:Terminals").GetChildren();
List<Terminal> terminalList = new List<Terminal>();
foreach (var keyValuePair in terminals)
{
Terminal termial = new Terminal()
{
Name = keyValuePair.Key,
Description = keyValuePair.Value
};
terminalList.Add(termial);
}
SundryOptions sundryOption = new SundryOptions()
{
CookieName = cookieName,
HRAccessGroup = accessGroup,
Terminals = terminalList
};
我已经检查了您提供的确切配置,并且效果很好。
答案 2 :(得分:0)
如果Terminals是一个列表,则在您的appSettings中,它应该是一个数组,而不是对象。
"Terminals" : [
"Raucherplatz" : "tablet1.local",
"Service" : "tablet2.local",
"Technik" : "tablet3.local",
"Technik" : "tablet4.local",
"Container" : "tablet5.local"
]