在web.config中存储值——appSettings还是configSection——哪个更有效?

12

我正在编写一个可以使用几种不同主题的页面,并将每个主题的一些信息存储在web.config中。

创建一个新的sectionGroup并将所有内容存储在一起,还是仅将所有内容放入appSettings中更有效率?

使用configSection的解决方案。

<configSections>
    <sectionGroup name="SchedulerPage">
        <section name="Providers" type="System.Configuration.NameValueSectionHandler"/>
        <section name="Themes" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup>
</configSections>
<SchedulerPage>
    <Themes>
        <add key="PI" value="PISchedulerForm"/>
        <add key="UB" value="UBSchedulerForm"/>
    </Themes>
</SchedulerPage>

我使用以下代码访问configSection中的值:

    NameValueCollection themes = ConfigurationManager.GetSection("SchedulerPage/Themes") as NameValueCollection;
    String SchedulerTheme = themes["UB"];

appSettings解决方案

<appSettings>
    <add key="PITheme" value="PISchedulerForm"/>
    <add key="UBTheme" value="UBSchedulerForm"/>
</appSettings>

我使用以下代码来访问appSettings中的值:

    String SchedulerTheme = ConfigurationManager.AppSettings["UBSchedulerForm"].ToString();
3个回答

12

对于更复杂的配置设置,我会使用自定义配置部分来明确定义每个部分的角色,例如:

<appMonitoring enabled="true" smtpServer="xxx">
  <alertRecipients>
    <add name="me" email="me@me.com"/>
  </alertRecipient>
</appMonitoring>

在您的配置类中,您可以使用类似以下方式公开您的属性:

public class MonitoringConfig : ConfigurationSection
{
  [ConfigurationProperty("smtp", IsRequired = true)]
  public string Smtp
  {
    get { return this["smtp"] as string; }
  }
  public static MonitoringConfig GetConfig()
  {
    return ConfigurationManager.GetSection("appMonitoring") as MonitoringConfig
  }
}

您可以通过以下方式从您的代码中访问配置属性:

string smtp = MonitoringConfig.GetConfig().Smtp;

10

在效率方面不会有明显的差异。

如果您只需要名称/值对,那么AppSettings非常适合。

对于任何更复杂的情况,值得创建自定义配置部分。

对于您提到的示例,我会使用appSettings。


6

性能上没有区别,因为ConfigurationManager.AppSettings只是调用GetSection("appSettings")。如果您需要枚举所有键,则自定义部分比枚举所有appSettings并查找一些键前缀更好,但否则,除非您需要比NameValueCollection更复杂的东西,否则最好使用appSettings。


但是假设我们不断向appSettings添加值,列表变得非常庞大。枚举整个列表并查找所需的条目不会影响性能吗?我相信这就是框架所做的。它获取appSettings部分,然后枚举所有键值对以找到具有匹配键值的条目。 - ItsZeus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接