Logo

NHibernate

The object-relational mapper for .NET

Extending NHibernate's DriverConnectionProvider

Note: this was orginally posted on my own blog

Ahh, i'm finally able to use NHibernate again at work, so expect more NHibernate related posts in the future :)

Today i needed a way to add some functionality when NHibernate opens a database connection, and again when NHibernate closes the connection. When the connection is opened, i need to setup some context on the connection for auditing purposes and it needs to be cleared again when the connection is closed. So i started searching on how to plug this into NHibernate. As usual, this was trivially easy to do. All you need to do is create a type that implements the IConnectionProvider interface. In my case, i only needed to add a bit of behavior so i could just derive from NHibernate's standard DriverConnectionProvider class and add the stuff i needed at the right time:

    public class AuditingConnectionProvider : NHibernate.Connection.DriverConnectionProvider

    {

        public override IDbConnection GetConnection()

        {

            IDbConnection connection = base.GetConnection();

            SetContextInfo(connection);

            return connection;

        }

 

        public override void CloseConnection(IDbConnection connection)

        {

            ClearContextInfo(connection);

            base.CloseConnection(connection);

        }

 

        private void SetContextInfo(IDbConnection connection)

        {

            // ...

        }

 

        private void ClearContextInfo(IDbConnection connection)

        {

            // ...

        }

    }

Pretty simple huh? All you have to do now is to configure NHibernate to use this new ConnectionProvider in your hibernate.cfg.xml file:

    <property name="connection.provider">My.Assembly.AuditingConnectionProvider, My.Assembly</property>

Was that easy or what? If only all frameworks were extensible in such an easy manner ;)


Posted Thu, 18 September 2008 05:48:00 AM by DavyBrion
Filed under: provider, connection

comments powered by Disqus
© NHibernate Community 2024