【问题标题】:Where should I put my connection strings for my class library and how do I access them?我应该将我的类库的连接字符串放在哪里以及如何访问它们?
【发布时间】:2012-02-22 13:14:28
【问题描述】:

我有一个包含 4/5 个项目的解决方案。

我目前在 c# 文件中硬编码了我的域项目的连接字符串。

我想把它放在 web.config 或其他东西中。从我在这里和其他地方阅读的内容来看,我应该将这些连接字符串存储在调用应用程序的 Web 配置中吗?

如果是,我该如何访问它?

当我在我的类库中做这样的事情时:

ConnectionStringSettingsCollection connectionStrings =
    connectionStringsSection.ConnectionStrings;

找不到类型或命名空间,是我缺少引用还是什么?

【问题讨论】:

  • 出于某种奇怪的原因(微软,你知道的)默认情况下不引用所需的程序集。您必须手动将System.Configuration 程序集的引用添加到需要使用它的每个项目中。

标签: c# connection-string


【解决方案1】:

您需要在主项目中添加对System.Configuration 的引用。

那么你可以像这样访问连接字符串...

System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;//<- last bit for a string version of the full connection string

ConfigurationManager 还允许您从 web.config 文件访问许多其他有用的属性(这也适用于 app.config 文件)

【讨论】:

    【解决方案2】:

    使用您的主应用程序定义并访问类库

    ConnectionStrings:使用 System.Configuration 添加; 添加 ref : System.Configuration;

    ConfigurationManager.ConnectionStrings["key"]
    

    另类

    System.Configuration.ConfigurationSettings.AppSettings["key"])
    

    【讨论】:

    • 只有当您的连接字符串在“AppSettings”中时,它才真正应该在 web.config 文件的“ConnectionStrings”标签中
    • 为什么不使用ConfigurationManager 暴露的内置ConnectionStrings 部分?自 .NET 2.0 起,不鼓励使用 AppSettings 连接字符串。
    【解决方案3】:

    config 架构中有一个用于连接字符串的现有架构。

    这在&lt;configuration&gt; 元素下:

    <connectionStrings>
      <add name="example" connectionString="..."/>
    </connectionStrings>
    

    在您的代码中,您应该使用ConfigurationManager 来访问它们。为了获得对它的引用,您需要将 using System.Configuration; 命名空间添加到您的文件,并将 System.Configuration.dll 程序集引用添加到您的项目(如果还没有的话)。

    string conn = ConfigurationManager.ConnectionStrings["example"];
    

    【讨论】:

    • ConfigurationManager 是一个不错的选择,还有我现在记得的另外 2 个选择:注册表和二进制文件(使用二进制格式化程序),请检查:stackoverflow.com/questions/9375112/…
    • @AmenAyach - 由于 OP 专门询问了web.config,因此注册表和二进制文件并不适合。
    • @Oded 好的,我明白了我的问题。感谢您的帮助
    • @iKode - 您是否在项目中添加了对 System.Configuration.dll 的引用?
    • @Oded 就是这样,我以为我已经包含了它,因为我的文件中有一个“使用 System.Configuration”。还在适应 Visual Studio / asp.net 等 感谢您的帮助。
    【解决方案4】:

    在您的代码中使用它。

    String sqlDbConn = 
            ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString();
    

    名称也应该在您的网络配置中定义;

    <connectionStrings>
     <add name="ApplicationServices"
           connectionString="You database information"
          />
    
     </connectionStrings>
    

    并且还使用 System.Configuration 添加;命名空间

    【讨论】:

    • ToString() 调用是多余的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 2015-03-14
    • 2016-10-12
    • 2014-11-08
    • 2011-05-09
    • 1970-01-01
    • 2011-06-10
    相关资源
    最近更新 更多