Storing values in the web.config - appSettings or configSection - which is more efficient?

随声附和 提交于 2019-12-02 23:42:40

For more complex configuration setup, I would use a custom configuration section that clearly defines the roles of each section for example

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

In your configuration class you can expose your properties with something like

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

You can then access configuration properties in the following way from your code

string smtp = MonitoringConfig.GetConfig().Smtp;

There will be no measurable difference in terms of efficiency.

AppSettings is great if all you need are name/value pairs.

For anything more complex, it's worth creating a custom configuration section.

For the example you mention, I'd use appSettings.

There'll be no difference in performance, since ConfigurationManager.AppSettings just calls GetSection("appSettings") anyway. If you'll need to enumerate all the keys, then a custom section will be nicer than enumerating all of appSettings and looking for some prefix on the keys, but otherwise it's easier to stick to appSettings unless you need something more complex than a NameValueCollection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!