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, I'll show you how to switch NHibernate connection strings at runtime.
DynamicConnectionString
.NHibernate.dll
, NHibernate.ByteCode.Castle.dll
, log4net.dll
, and the Eg.Core
model from Chapter 1.System.Configuration
from the .NET framework.App.config
with a standard NHibernate and log4net configuration.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.ConnectionStrings; var connstr = connstrs[ANON_CONN_NAME]; if (IsAuthenticated()) connstr = connstrs[AUTH_CONN_NAME]; return connstr.ConnectionString; } } private bool IsAuthenticated() { var identity = WindowsIdentity.GetCurrent(); return identity != null && identity.IsAuthenticated; } }
App.config
:<add name="db" connectionString= "Server=.SQLExpress; Database=NHCookbook; User Id=AnonymousUser; Password=p455w0rd"/> <add name="auth_db" connectionString= "Server=.SQLExpress; Database=NHCookbook; Trusted_Connection=SSPI"/>
connection.provider
to DynamicConnectionString.DynamicConnectionProvider, DynamicConnectionString
Just like we did in our previous recipe, we are using a custom connection provider. However, this time, we only override the ConnectionString
property to return different connection strings for anonymous and authenticated users. We set the NHibernate configuration property connection.provider
to the assembly qualified name of our custom connection provider, and NHibernate handles the rest.
18.118.9.197