Commits

Douglas Aguiar  committed 8fbe692 Merge

merge

  • Participants
  • Parent commits 24771d2, c478153

Comments (0)

Files changed (4)

File LiteFx.NHibernate/ConfigurationManager.cs

+using System.Reflection;
+using System.Threading;
+using FluentNHibernate.Cfg;
+using FluentNHibernate.Conventions.Helpers;
+using NHibernate.Cfg;
+using NHibernate.Cfg.Loquacious;
+
+
+namespace LiteFx.Context.NHibernate
+{
+	public static class ConfigurationManager
+	{
+		private static Mutex _configMutex = new Mutex();
+
+		private static Configuration configuration;
+		/// <summary>
+		/// Propriedade privada para fazer o cache da configuração do NHibernate.
+		/// </summary>
+		public static Configuration Configuration
+		{
+			get
+			{
+				if (configuration == null)
+				{
+					try
+					{
+						_configMutex.WaitOne();
+
+						if (configuration == null)
+						{
+							configuration = new Configuration();
+							configuration.LinqToHqlGeneratorsRegistry<ExtendedLinqtoHqlGeneratorsRegistry>();
+
+							if (CustomConfiguration != null)
+								CustomConfiguration(configuration);
+
+							configuration = Fluently.Configure(configuration)
+									.Mappings(m =>
+									{
+										m.FluentMappings
+											.Conventions.Setup(s => s.Add(AutoImport.Never()))
+											.AddFromAssembly(AssemblyToConfigure);
+										m.HbmMappings
+											.AddFromAssembly(AssemblyToConfigure);
+									}).BuildConfiguration();
+						}
+
+					}
+					finally
+					{
+						_configMutex.ReleaseMutex();
+					}
+				}
+
+				return configuration;
+			}
+		}
+
+		public static Assembly AssemblyToConfigure { get; set; }
+
+		public delegate void CustomConfigurationDelegate(Configuration configuration);
+
+		public static CustomConfigurationDelegate CustomConfiguration { get; set; }
+
+	}
+}

File LiteFx.NHibernate/LiteFx.NHibernate.csproj

     <Compile Include="..\AssemblyVersion.cs">
       <Link>AssemblyVersion.cs</Link>
     </Compile>
+    <Compile Include="ConfigurationManager.cs" />
     <Compile Include="ExtendedEqualsGenerator.cs" />
     <Compile Include="NHibernateContextAdapter.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />

File LiteFx.NHibernate/NHibernateContextAdapter.cs

 
 namespace LiteFx.Context.NHibernate
 {
-    /// <summary>
-    /// NHibernate base context.
-    /// </summary>
-    /// <typeparam name="TId"></typeparam>
-    public abstract class NHibernateContextAdapter<TId> : IContext<TId>, IDisposable
-        where TId : IEquatable<TId>
-    {
-        private ISession currentSession;
-        /// <summary>
-        /// Current NHibernate Session.
-        /// </summary>
-        protected ISession CurrentSession
-        {
-            get
-            {
-                return currentSession ?? (currentSession = SessionFactoryManager.Current.GetCurrentSession());
-            }
-        }
+	/// <summary>
+	/// NHibernate base context.
+	/// </summary>
+	/// <typeparam name="TId"></typeparam>
+	public abstract class NHibernateContextAdapter<TId> : IContext<TId>, IDisposable
+		where TId : IEquatable<TId>
+	{
+		/// <summary>
+		/// Current NHibernate Session.
+		/// </summary>
+		protected ISession CurrentSession
+		{
+			get
+			{
+				return SessionFactoryManager.Current.GetCurrentSession();
+			}
+		}
 
-        #region IContext Members
-        /// <summary>
-        /// Get a queryable object of an especifique entity.
-        /// </summary>
-        /// <typeparam name="T">Entity type.</typeparam>
-        /// <returns>Queryable object.</returns>
-        public virtual IQueryable<T> GetQueryableObject<T>() where T : class
-        {
-            return CurrentSession.Query<T>();
-        }
+		#region IContext Members
+		/// <summary>
+		/// Get a queryable object of an especifique entity.
+		/// </summary>
+		/// <typeparam name="T">Entity type.</typeparam>
+		/// <returns>Queryable object.</returns>
+		public virtual IQueryable<T> GetQueryableObject<T>() where T : class
+		{
+			return CurrentSession.Query<T>();
+		}
 
-        /// <summary>
-        /// Exclui uma entidade do contexto pelo seu Identificador.
-        /// </summary>
-        /// <typeparam name="T">Tipo do entidade.</typeparam>
-        /// <param name="id">Identificador do entidade.</param>
-        public virtual T Delete<T>(TId id)
-        {
-            var obj = CurrentSession.Get<T>(id);
-            Delete(obj);
-            return obj;
-        }
+		/// <summary>
+		/// Exclui uma entidade do contexto pelo seu Identificador.
+		/// </summary>
+		/// <typeparam name="T">Tipo do entidade.</typeparam>
+		/// <param name="id">Identificador do entidade.</param>
+		public virtual T Delete<T>(TId id)
+		{
+			var obj = CurrentSession.Get<T>(id);
+			Delete(obj);
+			return obj;
+		}
 
-        /// <summary>
-        /// Exclui uma entidade do contexto.
-        /// </summary>
-        /// <param name="entity">Entidade que será exlcuida.</param>
-        public virtual void Delete(object entity)
-        {
-            CurrentSession.Delete(entity);
-        }
+		/// <summary>
+		/// Exclui uma entidade do contexto.
+		/// </summary>
+		/// <param name="entity">Entidade que será exlcuida.</param>
+		public virtual void Delete(object entity)
+		{
+			CurrentSession.Delete(entity);
+		}
 
-        /// <summary>
-        /// Salva uma entidade no contexto.
-        /// </summary>
-        /// <param name="entity">Entidade que será salva.</param>
-        public virtual void Save(object entity)
-        {
-            CurrentSession.SaveOrUpdate(entity);
-        }
+		/// <summary>
+		/// Salva uma entidade no contexto.
+		/// </summary>
+		/// <param name="entity">Entidade que será salva.</param>
+		public virtual void Save(object entity)
+		{
+			CurrentSession.SaveOrUpdate(entity);
+		}
 
-        /// <summary>
-        /// Remove o objeto do cache do contexto.
-        /// </summary>
-        /// <param name="entity">Objeto a ser removido do cache.</param>
-        public void Detach(object entity)
-        {
-            CurrentSession.Evict(entity);
-        }
+		/// <summary>
+		/// Remove o objeto do cache do contexto.
+		/// </summary>
+		/// <param name="entity">Objeto a ser removido do cache.</param>
+		public void Detach(object entity)
+		{
+			CurrentSession.Evict(entity);
+		}
 
-        /// <summary>
-        /// Salva as informações alteradas no contexto no banco de dados.
-        /// </summary>
-        public virtual void SaveContext()
-        {
-            SessionFactoryManager.Current.CommitTransaction();
-        }
-        #endregion
+		/// <summary>
+		/// Salva as informações alteradas no contexto no banco de dados.
+		/// </summary>
+		public virtual void SaveContext()
+		{
+			SessionFactoryManager.Current.CommitTransaction();
+		}
+		#endregion
 
-        #region IDisposable Members [Dispose pattern implementation]
+		#region IDisposable Members [Dispose pattern implementation]
 
-        /// <summary>
-        /// Implementação do Dipose Pattern.
-        /// </summary>
-        /// <remarks><a target="blank" href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Dispose Pattern</a>.</remarks>
-        private bool disposed;
+		/// <summary>
+		/// Implementação do Dipose Pattern.
+		/// </summary>
+		/// <remarks><a target="blank" href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Dispose Pattern</a>.</remarks>
+		private bool disposed;
 
-        /// <summary>
-        /// Libera todos os recursos utilizados pela classe.
-        /// Implementação do Dispose Pattern.
-        /// </summary>
-        /// <remarks><a target="blank" href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Dispose Pattern</a>.</remarks>
-        /// <param name="disposing">Usado para verificar se a chamada esta sendo feita pelo <see cref="GC"/> ou pela aplicação.</param>
-        protected virtual void Dispose(bool disposing)
-        {
-            if (disposed) return;
+		/// <summary>
+		/// Libera todos os recursos utilizados pela classe.
+		/// Implementação do Dispose Pattern.
+		/// </summary>
+		/// <remarks><a target="blank" href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Dispose Pattern</a>.</remarks>
+		/// <param name="disposing">Usado para verificar se a chamada esta sendo feita pelo <see cref="GC"/> ou pela aplicação.</param>
+		protected virtual void Dispose(bool disposing)
+		{
+			if (disposed) return;
 
-            if (disposing)
-            {
-                if (CurrentSession != null)
-                    CurrentSession.Dispose();
-            }
+			if (disposing)
+			{
+				if (CurrentSession != null)
+					CurrentSession.Dispose();
+			}
 
-            disposed = true;
-        }
+			disposed = true;
+		}
 
-        /// <summary>
-        /// Chamado pelo <see ref="GC" /> para liberar recursos que não estão sendo utilizados.
-        /// Implementação do Dipose Pattern.
-        /// </summary>
-        /// <remarks><a target="blank" href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Dispose Pattern</a>.</remarks>
-        ~NHibernateContextAdapter()
-        {
-            Dispose(false);
-        }
+		/// <summary>
+		/// Chamado pelo <see ref="GC" /> para liberar recursos que não estão sendo utilizados.
+		/// Implementação do Dipose Pattern.
+		/// </summary>
+		/// <remarks><a target="blank" href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Dispose Pattern</a>.</remarks>
+		~NHibernateContextAdapter()
+		{
+			Dispose(false);
+		}
 
-        /// <summary>
-        /// Libera todos os recursos utilizados pela classe.
-        /// Implementação do Dipose Pattern.
-        /// </summary>
-        /// <remarks><a target="blank" href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Dispose Pattern</a>.</remarks>
-        public void Dispose()
-        {
-            Dispose(true);
-            GC.SuppressFinalize(this);
-        }
-        #endregion
-    }
+		/// <summary>
+		/// Libera todos os recursos utilizados pela classe.
+		/// Implementação do Dipose Pattern.
+		/// </summary>
+		/// <remarks><a target="blank" href="http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx">Dispose Pattern</a>.</remarks>
+		public void Dispose()
+		{
+			Dispose(true);
+			GC.SuppressFinalize(this);
+		}
+		#endregion
+	}
 }

File LiteFx.NHibernate/SessionFactoryManager.cs

-using System.Reflection;
+using System;
 using System.Threading;
-using FluentNHibernate.Cfg;
-using FluentNHibernate.Conventions.Helpers;
 using Microsoft.Practices.ServiceLocation;
 using NHibernate;
-using NHibernate.Cfg;
-using NHibernate.Cfg.Loquacious;
-using NHibernate.Context;
 
 namespace LiteFx.Context.NHibernate
 {
 	public abstract class SessionFactoryManager
 	{
-		private static SessionFactoryManager current;
 		public static SessionFactoryManager Current
 		{
 			get
 			{
-				return current ?? (current = ServiceLocator.Current.GetInstance<SessionFactoryManager>());
+				return ServiceLocator.Current.GetInstance<SessionFactoryManager>();
 			}
 		}
 
-		private static Mutex _configMutex = new Mutex();
-		private static Mutex _sessionMutex = new Mutex();
-
-		private Configuration configuration;
-		/// <summary>
-		/// Propriedade privada para fazer o cache da configuração do NHibernate.
-		/// </summary>
-		protected Configuration Configuration
+		public SessionFactoryManager()
 		{
-			get
-			{
-				if (configuration == null)
-				{
-					_configMutex.WaitOne();
-
-					if (configuration == null)
-					{
-						configuration = new Configuration();
-						configuration.LinqToHqlGeneratorsRegistry<ExtendedLinqtoHqlGeneratorsRegistry>();
-
-						CustomConfiguration(configuration);
-
-						configuration = Fluently.Configure(configuration)
-								.Mappings(m =>
-								{
-									m.FluentMappings
-										.Conventions.Setup(s => s.Add(AutoImport.Never()))
-										.AddFromAssembly(AssemblyToConfigure);
-									m.HbmMappings
-										.AddFromAssembly(AssemblyToConfigure);
-								}).BuildConfiguration();
-					}
-
-					_configMutex.ReleaseMutex();
-				}
-
-				return configuration;
-			}
+			id = Guid.NewGuid();
 		}
 
-		/// <summary>
-		/// Override to make custom configuration in NHibernate configuration class.
-		/// </summary>
-		/// <param name="configuration"></param>
-		protected virtual void CustomConfiguration(Configuration configuration) { }
+		private Guid id;
+		public Guid Id { get { return id; } }
 
-		/// <summary>
-		/// Has to be setted on constructor.
-		/// </summary>
-		protected abstract Assembly AssemblyToConfigure { get; }
+
+		private static Mutex _factoryMutex = new Mutex();
 
 		/// <summary>
 		/// Private sessionFactory.
 		/// </summary>
-		private ISessionFactory sessionFactory;
+		private static ISessionFactory sessionFactory;
 
 		/// <summary>
 		/// Propriedade privada para fazer o cache do sessionFactory do NHibernate.
 		/// </summary>
-		protected ISessionFactory SessionFactory
+		protected static ISessionFactory SessionFactory
 		{
 			get
 			{
 				if (sessionFactory == null)
 				{
-					sessionFactory = Configuration.BuildSessionFactory();
+					_factoryMutex.WaitOne();
+					if (sessionFactory == null)
+					{
+						sessionFactory = ConfigurationManager.Configuration.BuildSessionFactory();
+					}
+					_factoryMutex.ReleaseMutex();
 				}
 				return sessionFactory;
 			}
 		}
 
-		private static bool sessionOpened = false;
+		private ISession session;
 
 		public virtual ISession GetCurrentSession()
 		{
-			_sessionMutex.WaitOne();
-			if (!CurrentSessionContext.HasBind(SessionFactoryManager.Current.SessionFactory))
+			if (session == null)
 			{
-				ISession session = SessionFactory.OpenSession();
+				session = SessionFactory.OpenSession();
 				session.BeginTransaction();
-				CurrentSessionContext.Bind(session);
-				sessionOpened = true;
+				//CurrentSessionContext.Bind(session);
 			}
-			_sessionMutex.ReleaseMutex();
-			return SessionFactory.GetCurrentSession();
+
+			return session;
 		}
 
 		public virtual void DisposeSession()
 		{
-			if (sessionOpened)
+			if (session != null)
 			{
-				var session = CurrentSessionContext.Unbind(SessionFactory);
-				if (session != null)
-				{
-					session.Close();
-					session.Dispose();
-				}
-				sessionOpened = false;
+				//CurrentSessionContext.Unbind(SessionFactory);
+				session.Close();
+				session.Dispose();
+				session = null;
 			}
 		}
 
 		public virtual void CommitTransaction()
 		{
-			if (sessionOpened)
+			if (session != null)
 			{
-				var session = GetCurrentSession();
 				if (session.Transaction.IsActive)
 					session.Transaction.Commit();
 			}
 
 		public virtual void RollbackTransaction()
 		{
-			if (sessionOpened)
+			if (session != null)
 			{
-				var session = GetCurrentSession();
 				if (session.Transaction.IsActive)
 					session.Transaction.Rollback();
 			}
 
 		public virtual void Flush()
 		{
-			if (sessionOpened)
+			if (session != null)
 			{
-				var session = GetCurrentSession();
 				session.Flush();
 			}
 		}