Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I use the Unit of Work pattern on top of an NHibernate session?

When would I write a UoW implementation on top of what is already provided by NHibernate? Any real world examples?

like image 371
ng5000 Avatar asked Jun 11 '09 11:06

ng5000


1 Answers

The Unit Of Work you are describing is already provided by NHibernate so there is no reason to do such a unit of work.

What we have in our WCF Service is a higher level unit of work that contains information important in our application for the current unit of work. This includes abstracting the NHibernate ISession for us. When you break it down you have code that fits into three categories

  1. Code that needs to deal with a Unit Of Work. It doesn't matter who backs the unit of work. It could be NHibernate, iBatis or a custom ORM. All the code needs to do is Load, Rollback, Save, etc. It doesn't nor should it care about the mechanism used to do so.

  2. Code that needs to deal with an ISession directly because it's doing NHibernate specific things. Usually this has to do with complex queries that need to be created.

  3. Doesn't need to know that it's running in a Unit Of Work or access the ISession. We can completely ignore this as part of this discussion.

While code in 1. could just work against an ISession our preference is to try to abstract away things in the code that we do not directly control or that could change. This has value for two reasons.

  • When we started we weren't 100% sold on NHibernate. We were considering iBatis or something custom. Obviously this is no longer an issue.

  • The entire team are not experts in NHibernate nor do we want them to be. For the most part people write code that fits into category 1. and all they know about is our Unit Of Work. When code in category 2. has to get written it gets written by the people on the team that understand NHibernate well.

So to close I would say that the type of Unit Of Work you are talking about is not needed I would suggest that a higher level Unit of Work can provide a lot of value.

like image 149
Shane Courtrille Avatar answered Nov 15 '22 10:11

Shane Courtrille