Programmatically setting a connectionString property
The application we are developing will be installed at different locations and consequently will need to connect to a local SQL Server instance.
Rather than build separate configurations and installers for every site, we’re planning to store this information centrally. The application then uses a web service to retrieve the appropriate configuration information for its site.
As we are using NHibernate/ActiveRecord with the database configuration being loaded though the Castle ActiveRecord Integration Facility, the database name is indicated through naming a connection string (by specifying the config key ‘hibernate.connection.connection_string_name’). The difficulty is that this appears to be loaded the first time Windsor loads the config file. What we need is a way of replacing the connection string that was read from the app.config file with one that we’ve retrieved from the web service.
The main problem that needed to be overcome is that .NET doesn’t allow you to change the connection strings after they are read from the app.config file. If you try to do it, it will throw a ConfigurationErrorsException with the message “The configuration is read only”. The following code illustrates this:
var settings = ConfigurationManager.ConnectionStrings[0];settings.ConnectionString = "blah";
Steve Michelotti describes how you can override ConnectionStringsSection’s IsReadOnly method, which would be fine for custom configuration sections but doesn’t work in this case as the class is sealed.
Dmitry suggests another approach, though at the time it was just an untested idea. ConnectionStringSection inherits from the abstract class ConfigurationElement. Using Reflector you can see that the default implementation of IsReadOnly just returns the value of a private field _bReadOnly, which is set to true.
We use reflection to locate the private field _bReadOnly and then force it to be false. eg.
var settings = ConfigurationManager.ConnectionStrings[ 0 ];var fi = typeof( ConfigurationElement ).GetField( "_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic );fi.SetValue(settings, false);settings.ConnectionString = "Data Source=Something";
This is a bit of a hack and obviously would fail should Microsoft choose to change the name of this private field in the future, but as long as we do this before the container loads the configuration, it means that in the example above, any reference to the first connection string will return our new value.
An alternate approach might be to implement a custom NHibernate configuration provider, but I’ll leave that exercise to the reader :-)
5 comments:
Just the type of solution I was looking for :-) I've had a hard time finding this... lots of posts about changing connection strings in the web.config file but few about changing them without updating the web.config.
Thanks for writing it up.
-Wes
Fine solution.
I try do the same with whole ConnectionStringCollection but this private field not changed to false.
var fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
//or
//var fi = typeof(ConfigurationElementCollection).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
fi.SetValue(System.Configuration.ConfigurationManager.ConnectionStrings, false);
What can be a problem?
thanks
Here's what I did. This post inspired me.
Public Shared Sub AddConnectionStringFromRegistry()
Dim csSettings As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("MyDBConnectionString")
If csSettings IsNot Nothing Then Return
csSettings = New ConnectionStringSettings("MyDBConnectionString", GetMyDBConnectionString(), "System.Data.SqlClient")
Dim cssc As ConnectionStringSettingsCollection = WebConfigurationManager.ConnectionStrings
Dim t As Type = cssc.GetType().BaseType ' System.Configuration.ConfigurationElementCollection
Dim fi As FieldInfo = t.GetField("bReadOnly", BindingFlags.Instance Or BindingFlags.NonPublic)
fi.SetValue(cssc, False)
WebConfigurationManager.ConnectionStrings.Add(csSettings)
End Sub
David please email me I have a question re: this post but it's too long to post here as a comment.
Great work! Thanks a lot for this!
Post a Comment