c# - 如何将 appsettings.json 中的 json 设置解析为 c#.net core 中的类

标签 c# .net-core configuration app-config configurationsection

我有一个像这样的 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/

相关文章:

.net - AWS EC2中的服务段错误

c# - 将 Web API Controller 端点添加到 Kestrel 工作程序项目

wcf - 在使用 Autofac 注入(inject)的 WCF 服务上配置绑定(bind)

java - Spring Security的几种不同的登录表单

xml - log4j2 - 限制日志文件的数量

c# - .Net中的Dictionary在并行读写时是否有可能导致死锁?

c# - 为什么\character 在我的 @ 字符串中被加倍?

c# - IIS 8.5 上的 ASP.NET MVC 5 网页总是闲置

c# - SignalR 这个名字从何而来?

c# - Entity Framework 核心 : how to map multiple objects of the same type