我想结合这应该由appsettings.json文件来填充一个自定义的配置对象。如何使用.net核心应用程序中的IConfiguration绑定多级配置对象?
我的AppSettings看起来有点像:
{
"Logging": {
"IncludeScopes": true,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Settings": {
"Foo": {
"Interval": 30,
"Count": 10
}
}
}
的设置类的样子:
public class Settings
{
public Foo myFoo {get;set;}
}
public class Foo
{
public int Interval {get;set;}
public int Count {get;set;}
public Foo()
{}
// This is used for unit testing. Should be irrelevant to this question, but included here for completeness' sake.
public Foo(int interval, int count)
{
this.Interval = interval;
this.Count = count;
}
}
当我尝试配置绑定到一个对象时,它的工作原理的最低水平:
Foo myFoo = Configuration.GetSection("Settings:Foo").Get<Foo>();
myFoo
正确具有Interval
和Count
,值分别设置为30和10。
但这并不:
Settings mySettings = Configuration.GetSection("Settings").Get<Settings>();
mySettings
具有空foo
。
令人沮丧的是,如果我使用调试器,我可以看到必需的数据是从appsettings.json文件读入的。我可以分解到Configuration => Non-Public Members => _providers => [0] => Data
并查看我需要的所有信息。它只是不会绑定一个复杂的对象。
请问你设置类是什么样子? – Tseng
如何定义“Foo”和“Settings”? – haim770
@ haim770我已经添加了类定义。 – Necoras