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…

  1. Start a new console application project named DynamicConnectionString.
  2. Add references to NHibernate.dll, log4net.dll, and the Eg.Core model from Chapter 1, The Configuration and Schema.
  3. Add a reference to System.Configuration from the .NET framework.
  4. Set up App.config with a standard NHibernate and log4net configuration.
  5. 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.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;
      }
    
    }
  6. Add the following two connection strings to 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"/>
  7. Set the NHibernate property connection.provider to DynamicConnectionString.DynamicConnectionProvider, DynamicConnectionString.
  8. Build and run the program.

How it works…

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.

See also

  • Setting Microsoft SQL's Context_Info
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.174.253