views:

165

answers:

2

Hi,

If I have 10 database calls on my web page, and none of them require any transactions etc. They are simply getting data from the database (reads), should I still use the unit of work class?

Is it because creating a new session per database call is too expensive?

A: 

With NHibernate, session factory creation is very expensive (so you'll want to cache the session factory once it's created, probably on the HttpApplication) but session creation is very cheap. In other words, if it keeps your code cleaner, multiple session creations is not necessarily a bad thing. I think the NH documentation says it best:

An ISessionFactory is an expensive-to-create, threadsafe object intended to be shared by all application threads. An ISession is an inexpensive, non-threadsafe object that should be used once, for a single business process, and then discarded.

So, using the UoW pattern is probably not more efficient due to the extra overhead, but it's a good practice and the overhead is probably not going to hurt you. Premature optimization and all that.

Stuart Childs
A: 

Yes, you should use a transaction. From Ayende's blog:

"NHibernate assume that all access to the database is done under a transaction, and strongly discourage any use of the session without a transaction."

For more details, here's a link to his blog posting:

http://ayende.com/Blog/archive/2008/12/28/nh-prof-alerts-use-of-implicit-transactions-is-discouraged.aspx

Rob Scott