【问题标题】:Switching between groups of config values在配置值组之间切换
【发布时间】:2014-08-13 16:35:41
【问题描述】:

我的 App.Config 文件中有少量条目,这些条目会根据我正在进行的测试类型而改变。有没有办法告诉应用程序使用哪组设置?下面我模拟了一个我想到的App.Config 示例。

<configuration>
  <appSettings>
    <TestingScenario name="Scenario1">
      <add key="ApiKey" value="XXXXXXXXXXXXXXXXXXX" />
      <add key="UserName" value="XXXXXXXXXXXXXXXXXXX" />
      <add key="TokenId" value="XXXXXXXXXXXXXXXXXXX" />
    </TestingScenario>
    <TestingScenario name="Scenario2">
      <add key="ApiKey" value="XXXXXXXXXXXXXXXXXXX" />
      <add key="UserName" value="XXXXXXXXXXXXXXXXXXX" />
      <add key="TokenId" value="XXXXXXXXXXXXXXXXXXX" />
    </TestingScenario>
  </appSettings>
</configuration>

有没有办法让应用程序在一种情况下使用 Scenario1 而在另一种情况下使用 Scenario2?确定在代码中使用哪个场景会很好,因为它仍然可以让我不必注释和粘贴配置值。

【问题讨论】:

    标签: .net configuration app-config


    【解决方案1】:

    你不能这样自定义 appSettings;相反,您需要创建自己的自定义配置部分。这里有一些文章来看看它的能力:

    http://dotnetslackers.com/articles/customconfiguration/Custom_Configuration_Sections.aspx http://dotnetslackers.com/articles/customconfiguration/Configuration_Section_Validators.aspx http://dotnetslackers.com/articles/customconfiguration/Custom_Configuration_Collections.aspx

    这个想法是你创建一个继承自 ConfigurationSection 的类,然后在你可以设置的部分上定义属性,类似于:

    [ConfigurationProperty("DisplayInformation", DefaultValue=true)]
    public bool DisplayInformation
    {
        get
        {
           return (bool)this["DisplayInformation"];
        }
        set
        {
            this["DisplayInformation"] = value;
        }
    }
    

    一篇文章包括如何做集合,在你的例子中appSettings是ConfigurationSection,TestingScenario是appSettings类的集合中的项目列表,key和value是列表中实体的属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-07
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-25
      • 1970-01-01
      相关资源
      最近更新 更多