Nhibernate Unit of Work & multiple reuqests

time to read 2 min | 284 words

Another post request from the forum:


I'd love to get some detail on how to make the most of NHibernate's unit of work capability in a web app scenario.

It seems like in a web app, because your unit of work may be split across multiple web requests (and therefore sessions), it's hard to use NHibernate's change tracking etc effectively and I find myself doing unit of work tracking myself.

This seems to lead inevitably to an anaemic domain model and feels like fighting the tool.

Well, I am going to take that in two parts. First, having a unit of work that span requests is something that is possible (and I’ll discuss how to implement shortly), but I don’t recommend it. It is much easier to build your application so each request is a single unit of work.

Now, about actually implement a request that spans multiple requests, it is not really hard. It is called long conversation, or session per business transaction. Here is a detailed explanation on how NHibernate Burrow is achieving this.

But basically, it is quite simple. You set the session’s flush mode to Never, and you store NHibernate’s session in the ASP.Net session. Now, for each request, you can get the NHibernate session for the ASP.Net session and continue working with the same session and entities, taking advantage of change tracking, transparent persistence and all the other features that make NHibernate easy.

There are several frameworks out there that would handle this for you, Burrow, as I mentioned and Rhino Commons as well.