2016-12-28 30 views
0

我想结合这应该由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正确具有IntervalCount,值分别设置为30和10。

但这并不:

Settings mySettings = Configuration.GetSection("Settings").Get<Settings>(); 

mySettings具有空foo

令人沮丧的是,如果我使用调试器,我可以看到必需的数据是从appsettings.json文件读入的。我可以分解到Configuration => Non-Public Members => _providers => [0] => Data并查看我需要的所有信息。它只是不会绑定一个复杂的对象。

+0

请问你设置类是什么样子? – Tseng

+0

如何定义“Foo”和“Settings”? – haim770

+0

@ haim770我已经添加了类定义。 – Necoras

回答

2

你的属性必须在“appsettings.json”的属性名称相匹配。

您必须将您的设置'myFoo属性重命名为Foo,因为这是json文件中的属性名称。

+0

看起来这是问题。我最终命名属性与对象相同,尽量减少混淆。现在我只需要获取字典(上面未提到的)映射。谢谢。 – Necoras

2

您还可以使用JsonProperty(包括在Newtonsoft.Json)注释告诉串行做什么样的下方。

public class Settings 
{ 
    [JsonProperty("Foo")] 
    public Foo myFoo {get;set;} 
} 
+0

我检查了你的代码,对不起,这不起作用 – Alex

+0

它怎么样? –

+0

你已经说过与JsonProperty属性绑定可以工作,但它没有。你可以看看示例应用程序https://github.com/akutyrev/SO-Configuration-binding-problem – Alex

相关问题