【发布时间】:2020-11-19 15:15:11
【问题描述】:
我有一个看起来像这样的 appsettings.json
{
"AppName": "my-app-service",
"MyModel": {
"MyList": [{
"CountryCode": "jp"
},{
"CountryCode": "us"
}]
}
}
现在,我有一个 POCO 文件,(省略了 MyList.cs,它有一个字符串键 countryCode)
public class MyModel
{
public IList<MyList> MyList;
}
我希望能够将 MyModel 注入到我的代码中的任何位置,我该怎么做?我看到人们在他们的 setup.cs 中这样做
services.Configure<MyModel>(Configuration.GetSection("MyModel"));
当我在构造函数的代码中使用IOption<MyModel> 时,我得到的只是空值。我哪里错了?
【问题讨论】:
-
您能否分享您将 json 转换为模型的代码?否则,您可能必须使用 Newtonsoft JSON 将其读入对象中。
-
@Slipoch 这就是我要问的问题。如何通过此配置魔术直接将 JSON 转换为“MyModel”?
-
您所描述的应该可以工作(配置 + IOptions)。如果您想验证它是否正确绑定,您可以使用
var o = new MyModel(); Configuration.GetSection("MyModel").Bind(o);,然后检查现在应该填充的o。如果您还没有通过传递引用获得Microsoft.Extensions.Configuration.Binder的引用,则可能需要它。 -
虽然现在更仔细地查看您的课程,但
MyList是一个字段。活页夹仅适用于 properties,因此请添加{ get; set; },您应该一切顺利 -
@pinkfloydx33 哇,这是有史以来最大的问题。谢谢!
标签: c# .net-core configuration app-config configurationsection