You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WorkerService配置文件中添加自定义对象列表

关于WorkerService配置List<MyConfigObject>的实现方案

核心结论

可以在配置文件中配置List<MyConfigObject>,根据项目框架不同,有两种主流实现方案,以下是具体操作步骤:


方案一:使用传统App.config(XML)配置

适用于基于.NET Framework的WorkerService,或必须使用XML格式配置的场景,需通过自定义配置节实现:

  1. 编写配置映射类
    创建三个类来映射自定义对象和列表结构:

    • 自定义对象的配置元素类:
      public class MyConfigElement : ConfigurationElement
      {
          [ConfigurationProperty("name", IsRequired = true)]
          public string Name => (string)this["name"];
      
          [ConfigurationProperty("value", IsRequired = true)]
          public int Value => (int)this["value"];
      }
      
    • 配置元素集合类:
      public class MyConfigElementCollection : ConfigurationElementCollection
      {
          protected override ConfigurationElement CreateNewElement()
          {
              return new MyConfigElement();
          }
      
          protected override object GetElementKey(ConfigurationElement element)
          {
              return ((MyConfigElement)element).Name;
          }
      
          public MyConfigElement this[int index] => (MyConfigElement)BaseGet(index);
      }
      
    • 自定义配置节类:
      public class MyConfigSection : ConfigurationSection
      {
          [ConfigurationProperty("items", IsDefaultCollection = false)]
          public MyConfigElementCollection Items => (MyConfigElementCollection)this["items"];
      }
      
  2. 在App.config中注册并配置
    先注册自定义配置节,再添加具体的列表项:

    <configuration>
      <configSections>
        <section name="myConfigList" type="YourNamespace.MyConfigSection, YourAssemblyName" />
      </configSections>
    
      <myConfigList>
        <items>
          <add name="Item1" value="100" />
          <add name="Item2" value="200" />
        </items>
      </myConfigList>
    </configuration>
    
  3. 在代码中读取配置

    var configSection = (MyConfigSection)ConfigurationManager.GetSection("myConfigList");
    List<MyConfigObject> myList = configSection.Items.Cast<MyConfigElement>()
        .Select(e => new MyConfigObject { Name = e.Name, Value = e.Value })
        .ToList();
    

方案二:使用JSON配置(推荐)

适用于.NET Core/.NET 5+的WorkerService,这是官方推荐方案,配置更直观、代码更简洁:

  1. 添加appsettings.json文件
    在项目中新建appsettings.json,右键设置其属性为「复制到输出目录:如果较新则复制」。

  2. 编写强类型配置类

    public class MyConfigObject
    {
        public string Name { get; set; }
        public int Value { get; set; }
    }
    
    // 可选:若需和其他配置分组,可创建配置容器类
    public class AppSettings
    {
        public List<MyConfigObject> MyConfigList { get; set; }
    }
    
  3. 在JSON中配置列表

    {
      "MyConfigList": [
        {
          "Name": "Item1",
          "Value": 100
        },
        {
          "Name": "Item2",
          "Value": 200
        }
      ]
    }
    
  4. 在代码中绑定配置
    在Program.cs中直接绑定到强类型对象:

    var builder = Host.CreateDefaultBuilder(args);
    builder.ConfigureServices((context, services) =>
    {
        // 方式1:直接绑定列表
        var myConfigList = new List<MyConfigObject>();
        context.Configuration.GetSection("MyConfigList").Bind(myConfigList);
    
        // 方式2:通过依赖注入使用IOptions
        services.Configure<AppSettings>(context.Configuration);
    });
    

    若用依赖注入,可在Worker类中直接注入IOptions<AppSettings>来获取配置。


方案对比

  • XML配置:兼容.NET Framework,但需编写大量配置映射类,操作繁琐。
  • JSON配置:.NET Core及以后的首选方案,配置结构直观,绑定代码简洁,读写效率更高。新项目强烈建议使用JSON配置替代传统App.config。

内容的提问来源于stack exchange,提问作者Eric Ouellet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 04:30:09