views:

302

answers:

2

Hi

I Have been struggeling with NHibernate session management and have now ended up with two possible solutions to meet a session per web request.

I'm using Windsor for IoC in an ASPNET mvc project

First solution is to open a session in begin_request and close/dispose it again in end_request. In Windsor setup I would have container.Register(Component.For().UsingFactoryMethod(() => SessionFactory.GetCurrentSession()).LifeStyle.Transient;

This solution creates the session per request and shares it through GetCurrentSession.

The second solution is to use Windsor like

container.Register(Component.For().UsingFactoryMethod(() => SessionFactory.OpenSession()).LifeStyle.PerWebRequest);

This sould also give me an session per web request and support constructor injection. It's a bit more simpel, but I need a second opinion.

Please let me know what you would prefer to use,

best regards Rasmus

A: 

I use a unit of work, which I configure per web request in the container. The unit of work does not just create a session, but it also commits and rolls back transactions. The main reason to use a unit of work is to make the database more stable. More information about the unit of work pattern can be found on here.

public interface INHiberanteUnitOfWork
{
    ISession session { get; }
    void Commit();
    void RollBack();
}
Paco
+1  A: 

I don't recommend any of those two solutions. Instead of trying to reinvent the wheel, use the NHibernate facility.

Mauricio Scheffer
What kind of wheel is going to be reinvented here?
Paco
@Paco: NHibernate session management with Windsor in a web application
Mauricio Scheffer