All posts tagged 'vs2008'

.NET Musings

Wandering thoughts of a developer, architect, speaker, and trainer

NAVIGATION - SEARCH

Extension Methods for ISession in NHibernate

Technorati Tags: ,,

In my last post, we examined some simple extension methods to get the basics out of the way. Now let's apply those in a real world way to save typing and clean up our code base for NHibernate.

Key to NHibernate is the ISession interface. In my implementation of NHibernateSessionManager, I found myself coding two cases extensively.

  1. Checking for open transactions
  2. "Safely" closing my session instance

The code for both of these cases is very straightforward, but it's a lot of typing! Unfortunately, I never took typing...

Let's look at the two cases:

Checking for an active transaction involves four steps:

  1. Ensure the transaction property of the session instance is not null,
  2. Ensure the transaction has not been committed,
  3. Ensure the transaction has not been rolled back, and
  4. Ensure the transaction is still active

Safely closing a session (in my implementation)
involves three steps:

  1. Check to see if the session is "Dirty", and if so, flush it
  2. Disconnection the session, and
  3. Close the session

I also set the session to null for good measure
(paranoia left over from the old days).

To convert these to Extension Methods, we start with a static class:

  1: using NHibernate;
  2: namespace NHibernateUtilities 
  3: {
  4:   public static NHibernageExtensionMethods 
  5:   {
  6:   }
  7: }
  8: 

Now, create static methods that take an ISession object as the
first parameter, decorated with the "this" modifier, and checks
for all the conditions:

  1: public static bool HasOpenTransactions(this ISession session) 
  2: {
  3:   return (session.Transaction != null &&
  4:            !session.Transaction.WasCommitted &&
  5:            !session.Transaction.WasRolledBack &&
  6:            session.Transaction.IsActive);
  7: }
  8: 
  9: public static void SafeClose(this ISession session) 
 10: {
 11:   if (session.IsDirty()) { session.Flush(); }
 12:   session.Disconnect();
 13:   session.Close();
 14:   session = null;
 15: }
 16: 

Now, in our session manager code, we can greatly simplify our
code:

  1: if (session.HasOpenTransactions()) 
  2: {
  3:   transaction.Rollback();
  4: }
  5: 

Again, it is immensely important to properly name your
extension methods for readability. There isn't any doubt what
the extension method "HasOpenTransactions" is checking for.


Happy Coding!

Managed Windows Shared Hosting by OrcsWeb