【问题标题】:Understanding App.config and using Configuration Manager: GetSection vs. ConnectionString了解 App.config 并使用配置管理器:GetSection 与 ConnectionString
【发布时间】:2015-09-11 09:00:23
【问题描述】:

对于某些情况,我想打开到数据库的连接并执行一些查询。

这是我的 App.config:

    <dbservers>
        <connectionStrings>
            <add name="Cube_ConnectionString" connectionString="OLEDB; Datasource=http://cube.com; Initial Catalog=BP" />
        </connectionStrings>
        <queries>
            <add connectionStringName="CubeConnectionString" usedBy="DataAccessor" connectionString="" />
        </queries>
    </dbservers>

这就是我打算检索连接字符串的方式:

    System.Configuration.ConfigurationManager.ConnectionStrings["Cube_ConnectionString"].ConnectionString;

我想知道最好使用 GetSection 还是 ConnectionString。他们两个会得到什么回报?这两种方法如何在这样的嵌套 XML 中发挥作用?

另外,将查询放入 app.config 的目的是什么?

提前致谢

【问题讨论】:

  • 什么是&lt;dbservers&gt;?那是自定义部分吗?
  • 是的,它是一个自定义部分。那是我有点不确定的部分。这会影响方法的使用方式吗?

标签: c# app-config configuration-files configurationmanager


【解决方案1】:

我认为ConnectionStrings 不会起作用,除非您将它们放在标准部分。如果您想要自定义 &lt;dbservers&gt; 部分,则必须改用 GetSection

这个功能有点尴尬,但非常有用。 How to: Create Custom Configuration Sections Using ConfigurationSection 是一个有用的指南。

基本上这归结为创建一个继承自ConfigurationSection 的类,并添加适当的属性(来自上述指南):

public class PageAppearanceSection : ConfigurationSection
{
    // Create a "remoteOnly" attribute.
    [ConfigurationProperty("remoteOnly", DefaultValue = "false", IsRequired = false)]
    public Boolean RemoteOnly
    {
        get
        { 
            return (Boolean)this["remoteOnly"]; 
        }
        set
        { 
            this["remoteOnly"] = value; 
        }
    }

    // Create a "font" element.
    [ConfigurationProperty("font")]
    public FontElement Font
    {
        get
        { 
            return (FontElement)this["font"]; }
        set
        { this["font"] = value; }
    }

    // Create a "color element."
    [ConfigurationProperty("color")]
    public ColorElement Color
    {
        get
        {
            return (ColorElement)this["color"];
        }
        set
        { this["color"] = value; }
    }
}

...然后在 app/web.config 中添加对您的部分的引用:

<configuration>
  <configSections>
    <section name="dbservers" type="Namespace.DbServersSection, YourAssembly"/>
  </configSections>
</configuration>

【讨论】:

  • 所以如果我调用 GetSection("dbservers/connectionStrings) 会起作用吗?
  • 我没有这样尝试过;我只完成了(DbServersConfig)GetSection("dbservers"),然后通过该对象访问了孩子。
  • 太棒了。这很有帮助。我会花些时间把它通读一遍。
猜你喜欢
  • 2023-03-21
  • 2013-08-01
  • 2016-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
  • 2015-07-03
相关资源
最近更新 更多