sexta-feira, 24 de julho de 2015

NHibernate - Session Manager

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lapuinka.Core;
using NHibernate;
using System.Web;

namespace Lapuinka.Data
{
    public class SessionManager
    {
        private const string Sessionkey = "NHIBERNATE.SESSION.LAPUINKA";

        private readonly ISessionFactory _sessionFactory;

        private SessionManager()
        {
            _sessionFactory = GlobalFactory.Container.Resolve<ISessionFactory>();
        }

        public ISession Session
        {
            get
            {
                ISession session = IsWebContext() ? HttpContext.Current.Items[Sessionkey] as ISession : _session;

                if (session != null && session.IsOpen)
                {
                    return session;
                }

                return OpenSession();
            }

            internal set
            {
                if (IsWebContext())
                {
                    HttpContext.Current.Items[Sessionkey] = value;
                }
                else
                {
                    _session = Session;
                }
            }
        }

        public ISessionFactory SessionFactory
        {
            get
            {
                return _sessionFactory;
            }
        }

        public ISession OpenSession()
        {
            ISession session = SessionFactory.OpenSession();
           
            if (IsWebContext())
            {
                if (HttpContext.Current.Items.Contains(Sessionkey))
                {
                    HttpContext.Current.Items[Sessionkey] = session;
                }
                else
                {
                    HttpContext.Current.Items.Add(Sessionkey, session);
                }
            }
            else
            {
                _session = session;
            }

            session.FlushMode = FlushMode.Commit;

            return session;
        }

        public bool HasOpenSession()
        {
            ISession session = IsWebContext() ? HttpContext.Current.Items[Sessionkey] as ISession : _session;

            if (session != null && session.IsOpen)
            {
                return true;
            }

            return false;
        }

        [ThreadStatic]
        private static ISession _session;

        private static bool IsWebContext()
        {
            return HttpContext.Current != null;
        }

        public static SessionManager Instance
        {
            get
            {
                return LazySingleton.LazyInstance;
            }
        }

        private static class LazySingleton
        {
            static LazySingleton()
            {
            }

            internal static readonly SessionManager LazyInstance = new SessionManager();
        }
    }
}


Postar um comentário