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.Core
model from Chapter 1, The Configuration and Schema. - Add a reference to
System.Configuration
from the .NET framework. - Set up
App.config
with a standard NHibernate and log4net configuration. - Add the following
DynamicConnectionProvider
class: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...