我的类库应该把连接字符串放在哪里?如何访问它们?

7

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

目前,我在一份C#文件中将我的域项目的连接字符串硬编码。

我想把它放到web.config或其他地方。根据我在这里和其他地方阅读的内容,我应该将这些连接字符串存储在调用应用程序的web config中?

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

当我在我的类库中执行以下操作时:

ConnectionStringSettingsCollection connectionStrings =
    connectionStringsSection.ConnectionStrings;

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


由于某些奇怪的原因(微软你懂得),所需的程序集不是默认引用的。您需要手动添加对 System.Configuration 程序集的引用,以便每个需要使用它的项目都能够使用它。 - Shadow The Spring Wizard
4个回答

6

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

然后您可以像这样访问连接字符串...

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

ConfigurationManager 还可以让您从 web.config 文件(对于 app.config 文件同样适用)中访问其他一些有用的属性


5

config模式中存在一个用于连接字符串的架构。

此内容位于<configuration>元素下:

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

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

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

ConfigurationManager是一个不错的选择,我现在记得另外两个选择:Registry和二进制文件(使用二进制格式化程序)。请查看此链接:https://dev59.com/YWDVa4cB1Zd3GeqPfqwa#9375425 - Amen Ayach
2
@AmenAyach - 由于OP特别询问了web.config,因此注册表和二进制文件并不是很适合。 - Oded
@iKode - 你的项目中是否已经添加了对 System.Configuration.dll 的引用? - Oded
@Oded,就是这个问题,我以为已经包含了它,因为我的文件中有“using System.Configuration”。还在逐渐适应Visual Studio/ASP.NET等。感谢您的帮助。 - Positonic
@iKode - 没问题。在文件中提到一个命名空间并不意味着它已被引用,正如你现在学到的那样... - Oded
我找不到配置元素。 - user1735921

4

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

连接字符串:添加using System.Configuration; 添加引用:System.Configuration;

ConfigurationManager.ConnectionStrings["key"]

替代方案

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

如果您的连接字符串在“AppSettings”中,它应该放在web.config文件的“ConnectionStrings”标签中。 - musefan
1
为什么不使用 ConfigurationManager 公开的内置 ConnectionStrings 部分?自 .NET 2.0 起,已经不建议使用 AppSettings 来存储连接字符串。 - Oded

0

在你的代码中使用这个。

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

名称还应在您的 Web 配置文件中定义;

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

 </connectionStrings>

并且添加 using System.Configuration; 命名空间


2
ToString()调用是多余的。 - Oded

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