views:

546

answers:

2

Using FluentNHibernate in a web application, I've created a singleton SessionFactory class to have the ability of the following:

SessionFactory.Instance //returns ISessionFactory

Is it common/best practice to open/close sessions as follows?

using(ISession session = SessionFactory.Instance.OpenSession())
{
    using(ITransaction transaction = session.BeginTransaction())
    {
     //some operation
    }
}

The above code would live in the respective repository classes for a given entity.

I've noticed there is a theme of creating a HttpModule to open the session at the start and stop of the application, but I'm wondering if this is situational or more common.

UPDATE

Going forward with the HttpModule, I have a similar thought:

With a repository class, I'm basically doing the following(config uses WebSessionContext):

using(ISession session = SessionFactory.Instance.GetCurrentSession())
{
    using(ITransaction transaction = session.BeginTransaction())
    {
        //some operation
    }
}
+5  A: 

If you're using a web application I would recommend using the HttpModule to open a session and close it on a request cycle. The session factory I would probably instantiate on the Application_Start.

For the repository objects I would pass the session to it via a constructor.

I personally don't think a repository object has enough information in order to decide what to do with the session.

Min
Right on. I was originally discouraged due to my lack of knowledge on the WebSessionContext, but the HttpModule(begin/end) functionality seems to be working fine.
Alexis Abril
+3  A: 

I think this would depend on your conversation

  • session-per-request
  • session-per-request-with-detached-objects
  • session-per-conversation

for more information about that look here

Here are some links on implementations

note the session can be injected into the Doa/respository.

for a complete architecture have a look at sharp architecture < this is based on best practice, and i would reconmend it highly

Summer of Nhibernate ep 13, is about sessions with Asp.Net

HTH

bones

dbones
Very useful set of links, Thanks.
ScottS