【问题标题】:Class Library Connection String Confusion类库连接字符串混淆
【发布时间】:2014-02-16 19:01:29
【问题描述】:

我设法让自己迷惑了...不难,我知道,并且正在寻找一些指导...

我已经编写了一个 dll,我现在开始在我的 Winforms UI 中使用它。

这是对此的后续问题:

Class Libray Connection String - How to change?

正如那篇文章所述,我已将 dll 中的 app.config 中的相同连接字符串设置添加到 UI 中的 App.config 中。

在我的 UI 中,我有一个文本框,用户可以在其中输入连接字符串并点击“保存”,它运行以下代码:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString = txtConnectionString.Text;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");

这似乎正确地更新了文件中的字符串。

但是,这就是以前的帖子让我感到困惑的地方......

只有在软件启动时才会读取该设置。不知何故,我需要更改 Belogix 解释的设置,我应该这样做:

var connectionString = "Data Source=MegaServer;Initial Catalog=MyDb; .. etc ..";
using (var db = new MyDataContext(connectionString))
{
   // This will connect to MegaServer...
}

但是,我在我的 dll 中这样调用函数:

List<Page> pages = Database.getlistOfPagesToScan();

我如何告诉该调用开始使用 UI 的 App.config 中新保存的连接字符串?

谁能解释一下?

谢谢

【问题讨论】:

  • 将连接字符串传递给函数,或者让函数查找它应该使用的连接字符串(或连接字符串更改时创建的 dbcontext)。

标签: c# winforms


【解决方案1】:

您应该从 dll 中的设置中获取连接字符串。您的答案实际上就在您发布的问题中。

使用这个:

var connectionString = config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString;

你也可以这样用:

string s = Properties.Settings.Default.ConnectionStr;
Console.WriteLine("Connection string from main app: " + s);

//
// When setting access modifier on Class library to `public`
//
s = ClassLibrary1.Properties.Settings.Default.ConnectionStr;
Console.WriteLine("Connection string from dll: " + s);

【讨论】:

    【解决方案2】:

    假设您正在使用ConfigurationManager 检索应用程序连接字符串,请尝试:

    ConfigurationManager.RefreshSection("connectionStrings");
    

    【讨论】:

      猜你喜欢
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多