5/24/2010

NHibernate Unit of Work Example

Several months ago, I blogged about implementing the Repository Pattern with NHibernate. The Repository Pattern functions as both a facade and an abstraction layer for your application's data access layer (DAL). The major drawback of this approach is that you're forced to disable lazy loading, which is a coveted feature of NHibernate. This spawned the creation of the Unit of Work pattern; essentially the Repository pattern implemented with session control.

While many Unit of Work facades already exist, they all share the common problem of being nearly as complicated using NHibernate directly, which undermines the purpose of the facade pattern. To that end, I have developed a Unit of Work implementation for NHibernate that hits the sweet spot between functionality and simplicity. I'll use my classic scenario of monkeys and bananas to illustrate how one might use this particular implementation:

using (var uow = new NHUnitOfWork(Properties.Settings.Default.DBConnStr))
{
    Monkey m = uow.Get<Monkey>(0);

    m.NumberOfBananas++;

    uow.Save(myObject);
}

This small snippet utilizes an atomic transaction with the database, which is essential when incrementing bananas in a database (remember race conditions!). This also solves the "lazy loading issue" with the Repository pattern, since all fields are accessible during the transaction. The transaction automatically begins when the "using" statement is executed, and the transaction commits at the end of the 'using' block (when NHUnitOfWork.Dispose() is called). No remembering to call "Initialize" or "Commit" functions - these are assumed. Simple.

It's way past my bed time so I will upload the code tomorrow. Good night!

Update: The code can be downloaded from the Google Code project nhibernate-unitofwork-example.