如何在 .net Core 应用程序中使用 IConfiguration 绑定多级配置对象? [英] How do I bind a multi level configuration object using IConfiguration in a .net Core application?
问题描述
我正在尝试绑定到应由 appsettings.json 文件填充的自定义配置对象.
I'm trying to bind to a custom configuration object which should be populated by an appsettings.json file.
我的应用设置看起来有点像:
My appsettings looks a bit like:
{
"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;
}
}
当我尝试将配置绑定到最低级别的对象时,它起作用了:
When I try to bind the Configuration to an object the lowest level it works:
Foo myFoo = Configuration.GetSection("Settings:Foo").Get<Foo>();
myFoo
正确地有一个 Interval
和一个 Count
,其值分别设置为 30 和 10.
myFoo
correctly has an Interval
and a Count
with values set to 30 and 10 respectively.
但这不会:
Settings mySettings = Configuration.GetSection("Settings").Get<Settings>();
mySettings
有一个空 foo
.
令人沮丧的是,如果我使用调试器,我可以看到正在从 appsettings.json 文件中读取必要的数据.我可以进入 Configuration =>非公共成员 =>_providers =>[0] =>数据
并查看我需要的所有信息.它只是不会绑定一个复杂的对象.
Frustratingly, if I use the debugger I can see that the necessary data is being read in from the appsettings.json file. I can step down into Configuration => Non-Public Members => _providers => [0] => Data
and see all of the information I need. It just won't bind for a complex object.
推荐答案
您的属性必须与appsettings.json"中的属性名称匹配.
Your property must match the property names in "appsettings.json".
您必须将 Settings 的 myFoo
属性重命名为 Foo
,因为这是 json 文件中的属性名称.
You must rename your Settings' myFoo
property into Foo
, because that's property name in the json file.
这篇关于如何在 .net Core 应用程序中使用 IConfiguration 绑定多级配置对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!