tags:

views:

366

answers:

5

Hi

They say that to build a session factory in NHibernate is expensive and that it should only happen once. I use a singleton approach on this. This is done on the first time that a session is requested.

My question : Would there every be a time when you should close the Session factory? If so, when would one do this?

+5  A: 

This is what i do in Java with Hibernate :

 public class HibernateUtil
{

    private static final SessionFactory sessionFactory;

    static
    {
     try
     {
      // Create the SessionFactory from hibernate.cfg.xml
      sessionFactory = new Configuration().configure().buildSessionFactory();
     }
     catch (Throwable ex)
     {
      // Make sure you log the exception, as it might be swallowed
      System.err.println("Initial SessionFactory creation failed." + ex);
      throw new ExceptionInInitializerError(ex);
     }
    }

    public static SessionFactory getSessionFactory()
    {
     return sessionFactory;
    }

}

You can free your SessionFactory when you don't need it anymore I guess, but honestly I've never closed my session factory

Lliane
Doing almost the same in .NET. Only configuration is little bit different because of FluentNHibernate.
Arnis L.
+1  A: 

No, it dies with your program and that is fine.

svinto
A: 

As far as i know a session object keeps track of all entities retrieved and changed by your app. You should dispose of it and create a new one when you need a memory cleanup and a clean slate.

AZ
A: 

There should be only one instance of sessionfactory . The code above is not an example of singleton pattern. If you are working in an enterprise application, I would suggest use Spring with hibernate . That would help you out in managing transactions and take away all this headache of managing session factory

vsingh
A: 

To AZ: This is referring to the SessionFactory, not the session. Though I wouldn't say there should only be one instance of SessionFactory. There should be one per unique configuration. For instance, if a single app is connecting to 2 different databases, then you need 2 different SessionFactory instances.

Rich