Friday, June 24, 2011

Foray into Photon - Part 17 - Extracting the SessionFactory

So it seems that somehow this part was deleted yesterday, so I'm reposting it again today. We will be moving the ISessionFactory out of AegisBornPeer and instead be putting it into its own Singleton and using the Factory Method for creating new sessions. Go ahead and open up AegisBornPeer and delete CreateSessionFactory, the SessionFactory property, and the initialization statement in the constructor. Next we will be creating a new class called NHibernateHelper. As I said before it will be using the Singleton and Factory Method patterns. Here is the entire class:


using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;


namespace AegisBorn
{
    public class NHibernateHelper
    {
        private static ISessionFactory _sessionFactory;


        private static ISessionFactory SessionFactory
        {
            get
            {
                if (_sessionFactory == null)
                    InitializeSessionFactory();
                
                return _sessionFactory;
            }
        }


        private static void InitializeSessionFactory()
        {
            _sessionFactory = Fluently.Configure()
              .Database(
                MySQLConfiguration.Standard
                .ConnectionString(cs => cs.Server("localhost")
                .Database("cjrgam5_ab")
                .Username("cjrgam5_ab")
                .Password("user_ab1!")))
              .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf())
              .BuildSessionFactory();
        }


        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}

As you can see, the InitializeSessionFactory is almost exactly the same as CreateSessionFactory was except that we store the value locally in the singleton. Next you can see the factory method OpenSession that returns a new session to us. In AegisBornPeer you can replace the call to CreateSessionFactory with NHibernateHelper.OpenSession(); This also gives us the ability to use it in other listeners and not just the peer.

This lesson is rather small, next time we will be implementing the rest of the client side of the login by switching scenes and doing the setup necessary for the character select. Stay tuned.

No comments: