views:

172

answers:

3

Hi,

I am building a web application, and whenever I make a database call I need a session.

I understand creating a session object is very expensive.

I am following the repository pattern here: http://blogs.hibernatingrhinos.com/nhibernate/archive/0001/01/01/the-repository-pattern.aspx

He uses something called a UnitOfWork to get the session.

For a web application, shouldn't I be storing the Session in Request.Items collection? So its only created once per request?

Do I really need UofW?

A: 

In the case of NHibernate the key class is the SessionFactory, which SessionProvider is taking care of for you (if you implement it like that). Keep the SessionFactory alive, and it handles the sessions for you.

I've also seem people save the SessionFactory in their IoC.

Chris Brandsma
+1  A: 

The session IS the unit of work - its basically used to store changes until you flush them to the db. Save a static session factory at startup, and use that to create one session per web request - Request.Items seems a valid place to put the session.

The repository pattern is a wrapper over the unit of work. The repository pattern differs from the UoW pattern in that repo.Save(obj) should save the obj to the db straight away, while the UoW waits for a flush.

My advice would be to skip the repository pattern and use the ISession directly (see http://ayende.com/Blog/archive/2009/04/17/repository-is-the-new-singleton.aspx)

mcintyre321
I want to use the repository pattern because it gives me basic crud for all my entities w/o 0 code written, how can that be bad?!:)
mrblah
The ISession interface already give you basic CRUD (.Get<T>(), .Load<T>, .Delete, .SaveOrUpdate) and complex querying using either HQL, criteria API or NHibernate.Linq.
mcintyre321
Also see http://ayende.com/Blog/archive/2009/08/05/do-you-need-a-framework.aspx
mcintyre321
A: 

Use this to manage your sessions:

HybridSessionBuilder

It manages and gives you access to a single session that's used across the entire application.

Spencer Ruport