Technorati Tags:
NHibernate,
C#,
VS2008 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.
- Checking for open transactions
- "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:
- Ensure the transaction property of the session instance is not null,
- Ensure the transaction has not been committed,
- Ensure the transaction has not been rolled back, and
- Ensure the transaction is still active
Safely closing a session (in my implementation)
involves three steps:
- Check to see if the session is "Dirty", and if so, flush it
- Disconnection the session, and
- 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!
1d7d559e-be55-4838-b988-37f074285e23|0|.0|27604f05-86ad-47ef-9e05-950bb762570c