Alexis Abril
Alexis Abril

Reputation: 6459

Open/Close NHibernate Session

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
    }
}

Upvotes: 3

Views: 11309

Answers (2)

dbones
dbones

Reputation: 4504

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

Upvotes: 8

Min
Min

Reputation: 2975

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.

Upvotes: 9

Related Questions