简体   繁体   English

如何填充 IEnumerable<mytype> () 在 object 上通过配置?</mytype>

[英]How can I populated an IEnumerable<MyType>() on an object via configuration?

I'm trying to populate the following object using the Option pattern:我正在尝试使用选项模式填充以下 object :

public class MyParentPolicyOptions
{
    public IEnumerable<SomePolicySettings> SomePolicySettings { get; set; }
}

My config json looks like this:我的配置 json 看起来像这样:

{
  "MyParentPolicy": {
     "SomePolicies": [
     {
       "Name": "Default",
       "SomeSetting": 3,
       "IsHappy": false
     },
     {
       "Name": "Custom",
       "SomeSetting": 5,
       "IsHappy": true
     }
  ]
}

For the configuration I do something like this:对于配置,我执行以下操作:

serviceConfigurationDefinition.Optional("MyParentPolicy", Validators.MyParentPolicyOptions());

At the point of building the configuration builder I can see it has my properties as expected in the following pattern:在构建配置构建器时,我可以看到它具有以下模式中的预期属性:

{[MyParentPolicy:SomePolicies:0:Name, Default}]
{[MyParentPolicy:SomePolicies:0:SomeSetting, 3}]
{[MyParentPolicy:SomePolicies:0:IsHappy, false}]

However, after applying this configuration root to the ServiceConfigurationDefinition my actual MyParentPolicyOptions.SomePolicySettings is still null.但是,在将此配置根应用到 ServiceConfigurationDefinition 之后,我的实际 MyParentPolicyOptions.SomePolicySettings 仍然是 null。 It seems to work for other strongly typed objects but I can't get it to work for Lists / IEnumerables / arrays etc.它似乎适用于其他强类型对象,但我无法让它适用于 Lists / IEnumerables / arrays 等。

Just to add, I've just tried this with Dictionary<int, SomePolicySetting> in the hope that the automatic indexing would mean this was actually a dictionary type, but didn't work.补充一下,我刚刚用 Dictionary<int, SomePolicySetting> 尝试过这个,希望自动索引意味着这实际上是一个字典类型,但没有用。

I don't know for the serviceConfigurationDefinition.Optional() method you use.我不知道您使用的serviceConfigurationDefinition.Optional()方法。 In general I do it this way.一般来说,我是这样做的。 You're right IEnumerable is working.你是对的 IEnumerable 正在工作。 The issue is somewhere else in your code.问题出在代码中的其他地方。 The following example is working.以下示例正在运行。

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices( (context,services) =>
    {
        services.AddOptions();
        services.Configure<MyParentPolicy>(context.Configuration.GetSection("MyParentPolicy"));
        services.AddHostedService<Worker>();
    })
   .Build();
await host.RunAsync();

    public class MyParentPolicy
    {
        public IEnumerable<SomePolicySettings> SomePolicies { get; set; }
    }

    public class SomePolicySettings
    {
        public string Name { get; set; }
        public string SomeSetting { get; set; }
        public bool IsHappy { get; set; }  
    }

and appsettings.json :appsettings.json

{
  "MyParentPolicy": {
    "SomePolicies": [
      {
        "Name": "Default",
        "SomeSetting": 3,
        "IsHappy": false
      },
      {
        "Name": "Custom",
        "SomeSetting": 5,
        "IsHappy": true
      }
    ]
  }
}

And finally retrieve the options with IOptionsMonitor<MyParentPolicy> for example:最后使用IOptionsMonitor<MyParentPolicy>检索选项,例如:

        public Worker(ILogger<Worker> logger, IOptionsMonitor<MyParentPolicy> options)
        {
            _logger = logger;
            _parentPolicyOptions = options.CurrentValue;
        }

The easiest way is to get it from startup configuration最简单的方法是从启动配置中获取

List<SomePolicySettings> settings=  configuration.GetSection("MyParentPolicy")
.Get<MyParentPolicy>().SomePolicies.ToList();

if you want to use it everywhere inside of your app, you can create a service如果您想在应用程序内的任何地方使用它,您可以创建一个服务

startup启动

services.Configure<MyParentPolicy>(configuration.GetSection("MyParentPolicy"));
services.AddSingleton<SomePolicySettingsService>();

service class服务 class

public class SomePolicySettingsService
{
    private readonly  List<SomePolicySettings> _somePolicySettings;

    public SomePolicySettingsService(IOptions<MyParentPolicy> myParentPolicy)
    {
         _somePolicySettings  = myParentPolicy.Value.SomePolicies;
    }
    
    public SomePolicySettings GetDefaultPolicySettings()
    {
        return _somePolicySettings.FirstOrDefault(i=>i.Name=="Default");
    }
    public SomePolicySettings GetCustomPolicySettings()
    {
        return _somePolicySettings.FirstOrDefault(i => i.Name == "Custom");
    }
}

or instead of creating and injecting service, you can just inject " IOptions myParentPolicy" in the constructor everywhere you need.或者不用创建和注入服务,你可以在你需要的任何地方在构造函数中注入“IOptions myParentPolicy”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何转换IEnumerable <MyType> 进入MyList <MyType> ? - How can I convert an IEnumerable<MyType> into a MyList<MyType>? 如何将通用对象转换为MyType? - How can I cast a generic object to MyType? 如何通过参数执行其他对象配置? - How can I perform additional object configuration via parameter? ObservableCollection <MyType>上的扩展方法,MyType:IEnumerable <MyType> - Extension method on ObservableCollection<MyType>, MyType : IEnumerable<MyType> 我应该为对象和MyType覆盖==吗? - Should I override == for object and MyType? 将SelectedItems转换为IEnumerable <MyType> - Converting SelectedItems to IEnumerable<MyType> 为什么我得到“无法转换类型” IEnumerable <myType> &#39;到此LINQ查询上的&#39;myType&#39;? - Why do I get 'cannot convert type 'IEnumerable<myType>' to 'myType' on this LINQ query? 我该如何投射IEnumerable <?> 到IEnumerable <string> ? - How can I cast IEnumerable<?> to IEnumerable<string>? 如何减少IEnumerable <IEnumerable<Foo> &gt;到IEnumerable <Foo> ? - How can I reduce IEnumerable<IEnumerable<Foo>> to IEnumerable<Foo>? IEnumerable<object> a = 新的 IEnumerable<object> (); 我可以这样做吗?<div id="text_translate"><p> 我想创建一个 object IEnumerable&lt;object&gt;的新实例</p><p>我可以这样做吗?</p><pre> IEnumerable&lt;object&gt; a = new IEnumerable&lt;object&gt;();</pre></div></object></object> - IEnumerable<object> a = new IEnumerable<object>(); Can I do this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM