.NET DLL Settings and Config when there's a We

2019-03-20 03:58发布

问题:

My understanding is, that .NET doesn't really 'do' config files for DLLs - only the main Executable or Web App gets a config file, and all DLLs referenced by the Executable/Web App read from that.

But in VS2008, if you add a Web Reference to a Class Library (DLL) project, it adds a Settings.Settings file and an app.config file to the project. They contain the main URL for the Web Reference.

So what are these files for? There's no way for the DLL to read them unassisted, right?

edit: the contents of the app.config and Settings.Settings seem to make a difference though: changing (for example) the Web Reference URL in the DLL Project's app.config file on its own makes no difference, but if you edit the URL in the app.config and then open the Settings.Settings file, the changes you made in app.config then get copied into Settings.Settings. And then, the DLL picks up the new value at run time. How is it doing this?

edit: Part of my confusion here is because I'm not too clear on the difference between Settings.Settings and app.config and how they relate to each other, so maybe people can help out with that issue too.

回答1:

There's no way for the DLL to read them, but they're strong hints to a consumer of your DLL of what they might want to include in the real Settings/Config file

Edit

In response to the comment by OP - Whatever is last edited in the settings gets compiled into the code as a default to take if no setting of the correct name is present at runtime. So that's why that's working.



回答2:

Visual Studio has to add this stuff somewhere and it doesn't know which application you want to put it in. You can access the config for the DLL by doing the following:

var config = ConfigurationManager.OpenExeConfiguration("MyDll.dll.config");

The only time I've found this useful is when I wrote a plugin as a DLL for a 3rd party application and wanted my DLL to be configurable (not something most people do that often I suspect).

Usually though you will just move the config parts you need into your app.config or web.config.

Edit- In regards to your update that makes sense. Settings.settings application scoped settings come from the application's app.config file. For application scoped settings its really just a strongly typed class representing these settings.



回答3:

There is a possibility to read from config files in DLL. Just add an app.config file to the DLL project, and make sure you read the configuration settings from inside the DLL. When deployed, your config file needs to have the name "MyDLL.dll.config" (assuming your DLL is named "MyDLL.dll") and be in the same folder as the DLL.

The following code should return my connectionstring from my dll :

return ConfigurationManager.AppSettings["ConnectionString"];