The other day I was working on a project where I needed to have some configuration settings for an assembly that is installed in the GAC. I’ve needed this before, but I’ve always given up on it because I always had another way to store those settings. This time was different because I was writing a GAC assembly that was being used by another GAC assembly that was exposing a COM interface. Given this situation I didn’t have anywhere else to put the configuration settings.
Settings
So, after a little digging and searching on the Internet I came up with this approach for the development machine.
- Create the project for the assembly.
- Add an app.config file and populate the settings.
- Add a .snk file (created by sn –k [filename].snk at a “Visual Studio 2005 Command Prompt”)
- Modify the project setting to Sign the Assembly on the Signing tab.
- Modify the project settings to add the following build events on the Build tab (See notes below):
Pre-build
del "C:\WINDOWS\assembly\GAC_MSIL\$(TargetName)\[AssemblyVersion]__[AssemblyPublicKey]\$(TargetFileName).config"
"$(DevEnvDir)..\..\SDK\v2.0\bin\gacutil" /u "$(TargetName)"
Post-Build
"$(DevEnvDir)..\..\SDK\v2.0\bin\gacutil" /i "$(TargetPath)"
copy "$(TargetPath).config" "C:\WINDOWS\assembly\GAC_MSIL\$(TargetName)\ [AssemblyVersion]__[AssemblyPublicKey]\"
- Build the project and test the component
Notes on the build step:
First, to find the path of the GAC’d assembly you’ll need to do the following:
- Build the assembly without the copy/del .config part of the build events
- Open a command window
- Go to c:\windows\assembly; type "dir [assembly name]*.* /s"
- Copy the directory path and replace the "C:\WINDOWS\assembly\GAC_MSIL\$(TargetName)\ [AssemblyVersion]__[AssemblyPublicKey]\" with that directory
- Finally replace the assembly name with $(TargetName).
Once you've done this once and have your assembly version and assembly public key then you'll be able to reuse it in the future.
Second, you have to copy the .config file after you register the file in the GAC and delete the .config file before you unregister the file.
Code
Now, to use it in code you’ll need to load it in the following manner:
Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetExecutingAssembly().Location);
Once you have the Configuration object, then you can access your setting this way(assuming your setting in your config file is <add key="VerboseLogging" value="true"/>):
config.AppSettings.Settings["VerboseLogging"].Value;
Summary
So there you have it. It’s relatively straight forward, at least for the development machine. In a future blog I’ll tell you how to deploy it on a target machine…that is, once I figure it out. :-)