One of the most common issues people run into with WCF configuration, and .NET applications in general, is that configuration files appear to be fixed. You only have one configuration file for an executable, and you can’t use different configuration files as your exe.config while the application is running. Of course, you can always shut down the application, change the configuration, and then restart it with the new configuration file, but that’s tedious and oftentimes undesirable. In this blog post, I’ll show you how to easily get around this limitation.
Suppose you have the following simple configuration file:
<add key=“name“ value=“foo“/>
And let’s say you have the following code:
public static void Main()
static void ChangeConfiguration()
Configuration config = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection(“appSettings”);
The ChangeConfiguration method above opens up the configuration for the currently running executable, clears the appSettings dictionary, and then adds a new entry with value “bar” instead of “foo”. The main method simply checks the value of name before and after changing the configuration. If you run this code as is you’ll get the following output:
So even though you changed the configuration file, you’re not picking up on the appSetting’s new value. This is because the AppSettings section was cached when you first asked for it, and subsequent calls just use the cached version instead of reading from disk.
But now, if you add the following line of code to your Main method:
public static void Main()
Making sure to revert the configuration file to its original value “foo”, you get the following output:
So by calling RefreshSection, you’re telling the configuration API that it should invalidate the cached AppSettings section and instead read from disk on the next configuration call.
This is very useful in particular for WCF because it allows you to use different configuration files for different services or clients, and then just have the same application use all of those configuration files. In this way, you avoid having large configuration files that merge together the information for very many services or clients. Unfortunately, you can’t RefreshSection on a section group, only a section, so you’ll typically have to use the following calls to refresh WCF sections:
You may have to refresh other sections as well if you’re using some of the more advanced configuration sections.
Also worth noting: you don’t have to use Configuration.Save() to edit a configuration file, like I did above. You can change the file in any way you’d like, including changing the config file manually or using File.Copy().