Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate SessionFactory

Tags:

c#

nhibernate

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?

like image 244
Morph Avatar asked Jan 24 '23 07:01

Morph


2 Answers

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

like image 118
Lliane Avatar answered Feb 01 '23 08:02

Lliane


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.

like image 35
Rich Avatar answered Feb 01 '23 07:02

Rich