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.
1 comments: