Wednesday, January 13, 2010

NHibernate – Creating the session factory (Part 6)


In order to create an ISessionFactory instance, we need to create an instance of Configuration during application initialization and use it to set the database access and mapping information. Once configured, this instance is used to create the SessionFactory. As mentioned in the previous post,  session factory is not a lightweight component, so we’ll use a singleton class instance of the SessionFactory and be shared across the instances. I have created a SessionManager class in my sample that creates an instance of the SessionFactory and returns an ISession instance when required.
public class SessionManager
{
    public static SessionManager CurrentInstance
    {
        get
        {
            if (___CurrentInstance == null)
            {
                object __sync = new object();
                lock (__sync)
                    ___CurrentInstance = new SessionManager();
            }
            return ___CurrentInstance;
        }
    }

    public ISession Session
    {
        get
        {
            if (___sessionFactory == null)
            {
                object __sync = new object();
                lock (__sync)
                    ___sessionFactory = new Configuration()
                        .Configure()
                        .AddAssembly(typeof(BaseEntity<long>).Assembly)
                        .BuildSessionFactory();
            }
            return ___sessionFactory.OpenSession();
        }
    }

    private SessionManager() { }

    static SessionManager ___CurrentInstance;
    static ISessionFactory ___sessionFactory;
   
}
Next I’ll show how to configure the system for writing unit tests for the application.

No comments: