Using App.Config files in class libraries
January 17th, 2007[ Geek ]
Apologies upfront, this is nerdspeak, specifically C# nerdspeak, however, it’s something I’ve bumped into enough times that I felt it worth putting up. At least I’ll be able to find the answer easily next time I run into this.
Can you use an App.config file in a class library? Technically the answer is no, however, it’s not as limiting as it sounds. You can read an App.config file from an assembly, however, it must be in the context of the running assembly.
In the case of a large project with multiple assemblies, I typically want to have a single class that’s responsible for reading the configuration settings and making them available to other assemblies. So, is this even possible if you’d like that class to be in a library? Yes, however, you need to do some post-build work to make that happen.
Looking at a specific example, let’s say we have a console application named TheApp. That console app is only responsible for rendering it’s UI and all other work is done by multiple class libraries. We don’t want this assembly to contain the business logic related to reading configuration settings.
So we have another library, named Server. It has a static class named ConfigReader which reads the App.config file and makes settings available as discussed above. This can be done, however, the Server library will always look for and read the App.config file based on the running assembly, which in this case in the console application.
So, in order to make this work you have a few options, one of which is to simply have a nant task, or a post-build task, that copies the App.config file from your Server library into the console application’s bin directory, making sure to rename it based on the name of the console application, TheApp.exe.config. You can also generate this file, create from scratch, or simply keep it in the TheApp project itself.
If you grab the source code below and run it you’ll get an exception and it will appear as though it can’t read the App.config. That’s because one doesn’t exist in the bin directory you’re running in. Copy Server/App.config into TheApp bin directory and rename it to TheApp.exe.config and try again:
cp ../../../Server/App.config ./TheApp.exe.config
Again, another option would be to cut the App.config from the Server project and paste it into TheApp project. Build and you should be good. Now you have a class library reading your App.config file.
I’m not recommending you actually do any of this, just making sure you know it is an option. I find when you look around for information related to this, people often land on the conclusion that your only option is to read the App.config file in the console application (TheApp) which is not the case.