简体   繁体   中英

Class Library Connection String Confusion

I have managed to confuse myself... not difficult, I know, and am looking for some guidance...

I have written a dll which I am now starting to use in my Winforms UI.

This is a follow on question to this:

Class Libray Connection String - How to change?

As told in that post, I have added the identical connection string settings from the app.config in the dll to my App.config in my UI.

In my UI, I have a text box where the user can enter the connection string and hit "Save", which runs the following code:

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

Which seems to update the string in the file correctly.

But, and this is where the previous posting confuses me...

That setting only gets read when the software starts. Somehow I need to change the setting which Belogix has explained I should do like this:

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

But, I am calling functions in my dll like this:

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

How do I tell that call to start using the newly saved connection string from the UI's App.config?

Can anyone shed any light?

Thanks

You should get the connection string from the settings in the dll. Your answer is actually in the question you post.

Use this:

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

You can also use this:

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);

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

ConfigurationManager.RefreshSection("connectionStrings");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM