Using dynamic connection strings
There are cases where an application may need to change connection strings depending on some condition. This can be in the context of a multi-tenant application, or perhaps a database failover scenario. In this recipe, we'll show you how to switch NHibernate connection strings at runtime.
How to do it…
- Start a new console application project named
DynamicConnectionString. - Add references to
NHibernate.dll,log4net.dll, and theEg.Coremodel from Chapter 1, The Configuration and Schema. - Add a reference to
System.Configurationfrom the .NET framework. - Set up
App.configwith a standard NHibernate and log4net configuration. - Add the following
DynamicConnectionProviderclass:public class DynamicConnectionProvider : DriverConnectionProvider { private const string ANON_CONN_NAME = "db"; private const string AUTH_CONN_NAME = "auth_db"; protected override string ConnectionString { get { var connstrs = ConfigurationManager...