NHibernate and database connection recovery?

I am using NHibernate to connect to an old rdbms system. At high workload, the rdbms service fails. To ensure accessibility, we have the rdbms failover service. Is there a way to configure NHibernate to use the FailOver connection string when the primary connection is disconnected?

Additional Information: I am using Castle over NHibernate. If Castle provides failover processing, this will also do it for me.

+2
source share
2 answers

You can create your own NHibernate.Connection.IConnectionProvider, which provides support for switching to another resource.

It must be a subclass ConnectionProviderthat overrides CloseConnection() GetConnection()and Configure().

The connection provider is listed as a property in your hibernation configurationconnection.provider .

Here is an unverified implementation based on DriverConnectionProvider.

public class FailoverConnectionProvider : ConnectionProvider
{
    static string FailoverConnectionStringProperty = "connection.failover_connection_string";
    string failover_connstring;

    public override void CloseConnection(IDbConnection conn)
    {
        base.CloseConnection(conn);
        conn.Dispose();
    }

    public override IDbConnection GetConnection()
    {
        try {
            return GetConnection( ConnectionString );
        } catch {
            return GetConnection( failover_connstring );
        }
    }

    IDbConnection GetConnection( string connstring )
    {
        log.Debug("Obtaining IDbConnection from Driver");
        IDbConnection conn = Driver.CreateConnection();
        try {
            conn.ConnectionString = connstring;
            conn.Open();
        } catch (Exception) {
            conn.Dispose();
            throw;
        }

        return conn;
    }

    public override void Configure(IDictionary<string, string> settings)
    {
        base.Configure( settings );

        settings.TryGetValue(FailoverConnectionStringProperty, out failover_connstring);

        if (failover_connstring == null) {
            throw new HibernateException("Could not find connection string setting (set " + FailoverConnectionStringProperty + " property)");
        }
    }
}
+4
source

Nhiberbate uses ADO, which Failover Partner provides, for mirrored databases and connection / server failures. There is a stackOverflow question HERE which relates to a failover partner.

0
source

All Articles