tags:

views:

27

answers:

2

Hi

About the declaration of ISession.

Should we close the Session everytime we use it, or should we keep it open?

I'm asking this because in manual of NHibernate (nhforge.org) they recommend us to declare it once in Application_Start for example, but i don't know if we should close it everytime we use.

Thanks

A: 

You can keep one single static reference to a ISessionFactory, which can be indeed instantiated in Application_Start for web applications.

However, ISession must not be kept open and cannot be shared between two or more requests. You should adopt the "one session per request" pattern which allows you to build a single ISession for each HTTP request and dispose it safely once the request has been handled (this is assuming you are writing a web application).

For instance, the code handling NHibernate sessions in you project might look like this:

public static class NHibernateHelper {

    static ISessionFactory _factory;

    public static NHibernateHelper(){
        //This code runs once when the application starts
        //Use whatever is needed to build your ISessionFactory (read configuration, etc.)
        _factory = CreateYourSessionFactory();
    }

    const string SessionKey = "NhibernateSessionPerRequest";

    public static ISession OpenSession(){
        var context = HttpContext.Current;

        //Check whether there is an already open ISession for this request
        if(context != null && context.Items.ContainsKey(SessionKey)){
            //Return the open ISession
            return (ISession)context.Items[SessionKey];
        }
        else{
            //Create a new ISession and store it in HttpContext
            var newSession = _factory.OpenSession();
            if(context != null)
                context.Items[SessionKey] = newSession;

            return newSession;
        }
    }
}

This code is probably far to simple and has not been tested (nor compiled in fact), but it should work. For a more safe handling of your sessions you could also use an IoC container (Autofac for instance) and register your ISessions with a lifetime that depends on HTTP requests (Autofac will handle everything for you in that case).

Lck
A: 

Sessions should be closed when you are done with them. There are multiple possible ways to manage the lifetime of a session and choosing the right one is specific to each scenario. "Unit of Work" and "Session per Request" are the two most often used session lifetime management patterns.

In Application_Start, you should create the SessionFactory, not the Session. The SessionFactory does not need to be closed.

Michael Maddox