【问题标题】:Storing values in the web.config - appSettings or configSection - which is more efficient?将值存储在 web.config - appSettings 或 configSection - 哪个更有效?
【发布时间】:2010-09-17 07:25:52
【问题描述】:

我正在编写一个可以使用几个不同主题的页面,并且我将在 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();

【问题讨论】:

    标签: asp.net web-config performance appsettings configsection


    【解决方案1】:

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

    <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;
    

    【讨论】:

      【解决方案2】:

      在效率方面不会有可衡量的差异。

      如果您只需要名称/值对,AppSettings 就很棒。

      对于更复杂的事情,值得创建一个自定义配置部分。

      对于你提到的例子,我会使用 appSettings。

      【讨论】:

        【解决方案3】:

        性能不会有任何差异,因为 ConfigurationManager.AppSettings 无论如何都只是调用 GetSection("appSettings")。如果您需要枚举所有键,那么自定义部分将比枚举所有 appSettings 并在键上查找一些前缀更好,但否则更容易坚持 appSettings,除非您需要比 NameValueCollection 更复杂的东西。

        【讨论】:

        • 但是假设我们不断向 appSettings 添加值并且列表变得很大。枚举所有列表并找到需要的条目不会影响性能吗?我相信这就是框架的作用。它获取 appSettings 部分,然后枚举所有键值对以找到匹配键值的一对?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-09-11
        • 2010-11-22
        • 2012-09-21
        • 1970-01-01
        • 1970-01-01
        • 2017-03-23
        • 1970-01-01
        相关资源
        最近更新 更多