I will try and keep this short and I’ll start at a very high level in order to keep things very simple.
Concept: Unit of Work (UoW)
UoW is a general design pattern but rather than providing the generic (if I may say confusing) definition, I’ll just refer to the best definition I’ve come across for UoW as it relates to NH, which can be found here. I’ve reproduced the relevant content below:
Martin Fowler writes:
“When you’re pulling data in and out of a database, it’s important to keep track of what you’ve changed; otherwise, that data won’t be written back into the database. Similarly you have to insert new objects you create and remove any objects you delete.”
“A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you’re done, it figures out everything that needs to be done to alter the database as a result of your work.”
In this definition of work, the term “business transaction” can seem a bit vague and before addressing what it means, one needs to understand how the UoW pattern is implemented in NH.
Concept: NH Session
The UoW pattern is implemented using an NH Session, which incidententally does not have anything to do with a web session. As explained here,
In NHibernate we have the Session object which is a Unit of Work (UoW) container.
In simplistic terms, to “implement” a UoW of work in NH, you
- “Open” an NH Session
- Do some business transaction
- “Close” the NH Session
In the next post, I’ll detail how to actually use the NH Session object and implement a basic UoW.