扩展 App.config 中的元素

Extend an element in App.config

我们有一个 app.config 与 Carbonator 一起使用:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="carbonator" type="Crypton.Carbonator.Config.CarbonatorSection, Crypton.Carbonator"/>
  </configSections>

  <carbonator defaultCulture="en-US" logLevel="1" collectionInterval="1000" reportingInterval="1000" >
    <statsd server="127.0.0.1" port="8125" />
    <counters>
      <add path="processor_information.pct_processor_time.total" category="Processor" counter="% Processor Time" instance="_Total" />
      <add path="memory.available_MBytes" category="Memory" counter="Available MBytes" instance="" />
      <add path="memory.pct_commited_bytes_in_use" category="Memory" counter="% Committed Bytes In Use" instance="" />
    </counters>
  </carbonator>
</configuration>

我们希望允许用户在我们从 <counters> 元素引用的外部配置文件中配置他们自己的自定义计数器。例如,我们想让用户配置文件看起来像:

<add path="logical_disk.pct_free_space.C" category="LogicalDisk" counter="% Free Space" instance="C:" />
<add path="logical_disk.disk_read_bytes_per_sec.C" category="LogicalDisk" counter="Disk Read Bytes/sec" instance="C:" />
<add path="logical_disk.disk_write_bytes_per_sec.C" category="LogicalDisk" counter="Disk Write Bytes/sec" instance="C:" />

我什至不知道这在 appConfig 元素之外是否可行,但我们将不胜感激。

根据this answer it should be possible. Same way is also described in this article

但我认为这不是一个好主意,原因有一个 - 如果用户在他的配置扩展中犯了错误,它将阻止应用程序执行,因为应用程序配置变得无效。

我宁愿使用app.config文件中的配置来提供默认值并自己实现一些用户配置。在这种情况下,您可以使用您喜欢的任何配置格式,例如 JSON,这对用户来说也更好(更容易创建和编辑)。在您的应用程序中,您只需合并两个配置(app.config 值是默认值,将被用户的配置覆盖)。