我有一个像这样的 appsettings.json
{
"AppName": "my-app-service",
"MyModel": {
"MyList": [{
"CountryCode": "jp"
},{
"CountryCode": "us"
}]
}
}
现在,我有一个 POCO 文件,(省略了 MyList.cs,它有一个字符串键 countryCode)
public class MyModel
{
public IList<MyList> MyList;
}
我希望能够将 MyModel 注入(inject)到我的代码中的任何位置,我该怎么做?我看到人们在他们的 setup.cs 中这样做
services.Configure<MyModel>(Configuration.GetSection("MyModel"));
当我使用 IOption<MyModel>
时它看起来如何?在我的构造函数代码中,我只得到空值。我哪里错了?
最佳答案
你是对的:调用 Configure<T>
为 T
设置选项基础设施.这包括 IOptions<T>
, IOptionsMonitor<T>
和 IOptionsSnapshot<T>
.在其最简单 形式中,配置值使用 Action<T>
或在您的示例中绑定(bind)到特定的 IConfiguration
.您还可以堆叠多次调用 Configure
的任一形式。 .然后,这允许您接受 IOptions<T>
(或监视器/快照)在您的类的构造函数中。
确定是否绑定(bind)到 IConfigurationSection
的最简单方法按照您的预期工作是手动执行绑定(bind),然后检查值:
var opts = new MyClass();
var config = Configuration.GetSection("MyClass");
// bind manually
config.Bind(opts);
// now inspect opts
以上依赖于Microsoft.Extensions.Configuration.Binder
如果您引用 Options 基础设施,您应该已经将其作为传递依赖项拥有的包。
回到你的问题: Binder 只会绑定(bind) public
属性 默认情况下。在你的情况下 MyClass.MyList
是一个字段。要使绑定(bind)生效,您必须将其改为属性。
如果你想/需要绑定(bind)非 public
您可以传递 Action<BinderOptions>
的属性:
// manually
var opts = new MyClass();
var config = Configuration.GetSection("MyClass");
// bind manually
config.Bind(opts, o => o.BindNonPublicProperties = true);
// DI/services
var config = Configuration.GetSection("MyClass");
services.Configure<MyClass>(config, o => o.BindNonPublicProperties = true);
即使是 BinderOptions
仍然没有办法绑定(bind)到字段。另请注意,集合接口(interface)、数组和get
等事物的行为各不相同。只有属性。您可能需要稍微尝试一下,以确保按照您的意愿进行绑定(bind)。
关于c# - 如何将 appsettings.json 中的 json 设置解析为 c#.net core 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63163628/