【问题标题】:Passing connection string to dll?将连接字符串传递给dll?
【发布时间】:2012-07-11 10:44:16
【问题描述】:

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

这就是我设置库的方式

[解决方案文件]

  • 图书馆1
    • db.config
  • 图书馆2
    • 链接的 db.config

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

【问题讨论】:

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


    【解决方案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) 等等等等等等

    【讨论】:

    • 不能使用配置文件吗?
    【解决方案2】:

    回答你的第一个问题:

    我通常更喜欢使用这样的 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"));
    

    【讨论】:

    • 您在库中引用的配置文件还是调用库的应用程序?现在我的应用程序和类库中有一个 conStrings.config 文件,我使用 string connString = ConfigurationManager.ConnectionStrings["DBConnectMain"].ToString(); 调用它但这似乎不是一个好主意。
    • 我的代码只是展示了如何加载和使用任何配置文件。
    猜你喜欢
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 2022-07-23
    相关资源
    最近更新 更多