将动态应用程序配置绑定到 .Net Core 中的强类型模型中



>我正在尝试将应用程序配置绑定到强类型模型中。我的配置是动态类型的,所以我无法弄清楚如何将配置映射到模型中。下面是配置,

AppSettings.json

{
"Utility": {
"Log": {
"FileName": "D:\Log.txt"
},
"test1": {
"Path": "E:\Path1",
"Daystokeep": "0"
},
"test2": {
"Path": "E:\Path2",
"Daystokeep": "0"
},
"test3": {
"Path": "E:\Path3",
"Daystokeep": "0"
}
}
}

在这里,日志是静态的,test1、test2 和 test3 等是动态的。如果您能提出可能性,那将非常有帮助。

只需将字典添加到配置属性;

public class MyConfig {
public Dictionary<string, Config> Utility { get; set; }
}
public class Config {
public string Path { get; set; }
public int Daystokeep { get; set; }
}

您还可以对字典进行子类化,以捕获具有固定结构的其他值;

public UtilityConfig Utility { get; set; }
public UtilityConfig : Dictionary<string, Config> {
public AnotherConfigType Log { get; set; }
}

最新更新