Changing the ASP.Net web.config connectionstrings at runtime

So here’s an interesting challenge we had to overcome today: every developer in the team has small variations in his/her workstation setup. Instead of micro-managing each installation (we all know how developers love to be micro-managed and even more so how they love to be told how to set up their workstation), we thought we’d give a stab at changing the connections from the web.config at runtime.

Wait, aren’t there a million posts on how to do that already? Well, yes, but most of them use web.config transformations (which aren’t ran when you locally debug), or actually save the web.config (physically changing the file on disk so that the next developer that gets the default web.config is screwed).

What we wanted to do, is actually load the default web.config, but, per developer, change some of the in-memory values.
Turns out, all you need is a little reflection:

        private static void SetConnectionString(string name, string connectionString)
                .GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(ConfigurationManager.ConnectionStrings, false);
            var connection = System.Configuration.ConfigurationManager.ConnectionStrings[name];
                .GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(connection, false);
            connection.ConnectionString = connectionString;

Then, in your global.asax application_start method, before doing anything else:

#if BOB
  SetConnectionString("LocalSqlServer", "wow");
  SetConnectionString("DefaultConnection", "much monkey patch");
  SetConnectionString("AndAnother", "very connectionstring");  

Finally, each developer goes to the configuration manager (the dropdown next to ‘Debug’), creates a new configuration based on ‘debug’, then in the project properties > Build > adds the conditional compilation symbols BOB, CUSTOMCONNECTIONSTRINGS.
Now each developer can run his/her own configuration and manage how they’ve set up their own system, the code that does the monkey patching of the connection strings is not even included in the release output, and the actual web.config file is never modified and will always contain the default values.


5 thoughts on “Changing the ASP.Net web.config connectionstrings at runtime

  1. Pingback: Code Contracts - The Daily Six Pack: May 8, 2015

Leave a Reply


You are commenting using your account. Log Out /  Change )

Google photo


Twitter picture


Facebook photo


Connecting to %s