将连接字符串传递给dll?

时间:2012-07-11 18:28:08

标签: .net dll shared-libraries app-config

我正在尝试制作一些需要数据库访问的简单库。我没有得到的是如何将连接字符串传递给库...现在我在我的DLL中有一个db.config,但我不确定如何从dll等中引用它... < / p>

这就是我设置库的方式

[解决方案文件]

  • 分享帮助
    • db.config
  • Library2
    • 链接的db.config

<configuration>
        <!-- Connection string -->
    </configuration>
  1. 如何从dll中引用db.config?
  2. 如何从Web应用程序web.config中引用db.config?

2 个答案:

答案 0 :(得分:1)

真的很简单:

1)如果这恰好是.Net .dll,您可以将其存储在“app.config”或“web.config”中:

Example

<?xml version="1.0" encoding="utf-8" ?>
  <configuration>
    <connectionStrings>
      <add name="DigiBrd"
           connectionString="server=localhost;user id=****;Password=****;database=DigiBrd"
           providerName="MySql.Data.MySqlClient" />
  </connectionStrings>
</configuration>

String cnString =
  ConfigurationManager.ConnectionStrings["DigiBrd"].ConnectionString;

2)您还可以将连接字符串存储在.dll可以读取的任何位置。例如,您可以使用.ini文件或注册表。

3)您可以在.dll中实施getConnectionString()方法。

4)等等。

答案 1 :(得分:1)

回答你的第一个问题:

我通常更喜欢使用以下一种ConfigurationManager方法:

http://msdn.microsoft.com/en-us/library/ms224437.aspx

或者有XPath的旧式Xml:

XmlDocument webConfig = new XmlDocument();
webConfig.Load(dllConfigFileName);
XmlNode someNode = webConfig.SelectSingleNode("//configuration/appSettings/add[@key='someKey']");

或者更新的LINQ to XML:

XDocument document = XDocument.Load(configFileFullName);
XElement configurationElement = document.Element("configuration");
XElement appSettingsElement = configurationElement.Element("appSettings");
List<XElement> configSettings = new List<XElement>(appSettingsElement.Descendants("add"));
相关问题