Пример #1
0
 public static void UnbindSessionContext()
 {
     if (CurrentSessionContext.HasBind(SessionFactory))
     {
         CurrentSessionContext.Unbind(SessionFactory);
     }
 }
Пример #2
0
        public void EndTransaction(HttpActionExecutedContext filterContext)
        {
            if (!CurrentSessionContext.HasBind(_sessionFactory))
            {
                return;
            }
            var session = _sessionFactory.GetCurrentSession();

            if (session == null)
            {
                return;
            }
            if (!session.Transaction.IsActive)
            {
                return;
            }
            if (filterContext.Exception == null)
            {
                session.Flush();
                session.Transaction.Commit();
            }
            else
            {
                session.Transaction.Rollback();
            }
            TransactionHandled = true;
        }
Пример #3
0
 /// <summary>
 ///     Close an ISession and unbind it from the current
 ///     NHibernate Context.
 /// </summary>
 public static void CloseSession()
 {
     if (CurrentSessionContext.HasBind(SessionFactory))
     {
         var session = CurrentSessionContext.Unbind(SessionFactory);
         if (session == null)
         {
             return;
         }
         if (session.Transaction != null && session.Transaction.IsActive)
         {
             STrace.Error(typeof(NHibernateHelper).FullName, String.Format("A non closed transaction is Active at CloseSession()!: {0}", HttpContext.Current != null ?HttpContext.Current.Request.CurrentExecutionFilePath : "No context?"));
             try
             {
                 session.Transaction.Commit();
             }
             catch (Exception ex)
             {
                 STrace.Exception(typeof(NHibernateHelper).FullName, ex, "CloseSession();");
                 try
                 {
                     session.Transaction.Rollback();
                 }
                 catch (Exception ex2)
                 {
                     STrace.Exception(typeof(NHibernateHelper).FullName, ex2, "CloseSession(); doing rollback");
                 }
             }
         }
         session.Close();
         session.Dispose();
     }
 }
Пример #4
0
        public static ISession GetCurrentSession()
        {
            if (_sessionFactory == null)
            {
                if (HttpContext.Current == null)
                {
                    _sessionFactory = CreateSessionFactory <ThreadStaticSessionContext>();
                }
                else
                {
                    _sessionFactory = CreateSessionFactory <WebSessionContext>();
                }
            }

            if (CurrentSessionContext.HasBind(_sessionFactory))
            {
                return(_sessionFactory.GetCurrentSession());
            }

            ISession session = _sessionFactory.OpenSession();

            CurrentSessionContext.Bind(session);

            return(session);
        }
Пример #5
0
 public void CloseSession()
 {
     if (CurrentSessionContext.HasBind(SessionFactory))
     {
         CurrentSessionContext.Unbind(SessionFactory).Dispose();
     }
 }
Пример #6
0
        public void EndTransaction(System.Web.Http.Filters.HttpActionExecutedContext httpActionExecutedContext)
        {
            if (!CurrentSessionContext.HasBind(sessionFactory))
            {
                return;
            }

            var session = sessionFactory.GetCurrentSession();

            if (null == session)
            {
                return;
            }

            if (!session.Transaction.IsActive)
            {
                return;
            }

            if (httpActionExecutedContext.Exception == null)
            {
                session.Flush();
                session.Transaction.Commit();
            }
            else
            {
                session.Transaction.Rollback();
            }

            TransactionHandled = true;
        }
 private static void BindContext()
 {
     if (!CurrentSessionContext.HasBind(sessionFactory))
     {
         CurrentSessionContext.Bind(sessionFactory.OpenSession());
     }
 }
 private static void UnBindContext()
 {
     if (CurrentSessionContext.HasBind(sessionFactory))
     {
         CurrentSessionContext.Unbind(sessionFactory);
     }
 }
        public void MapContextThreadSafety()
        {
            using (var factory1 = cfg.BuildSessionFactory())
                using (var session1 = factory1.OpenSession())
                    using (var factory2 = cfg.BuildSessionFactory())
                        using (var session2 = factory2.OpenSession())
                        {
                            var thread1 = new Thread(() =>
                            {
                                CurrentSessionContext.Bind(session1);
                            });

                            var thread2 = new Thread(() =>
                            {
                                CurrentSessionContext.Bind(session2);
                            });

                            thread1.Start();
                            thread2.Start();
                            thread1.Join();
                            thread2.Join();

                            Assert.IsTrue(CurrentSessionContext.HasBind(factory1), $"No session bound to \"{nameof(factory1)}\" factory.");
                            Assert.IsTrue(CurrentSessionContext.HasBind(factory2), $"No session bound to \"{nameof(factory2)}\" factory.");
                        }
        }
Пример #10
0
 public void End()
 {
     if (_useSingletonSession)
     {
         lock (_lock)
         {
             if (_factory == null)
             {
                 return;
             }
             if (_singletonSession == null)
             {
                 return;
             }
             _singletonSession.Close();
         }
     }
     else
     {
         if (_factory == null)
         {
             return;
         }
         if (!CurrentSessionContext.HasBind(_factory))
         {
             return;
         }
         var session = CurrentSessionContext.Unbind(_factory);
         session.Close();
     }
 }
Пример #11
0
 private void BindSession()
 {
     if (!CurrentSessionContext.HasBind(_sessionFactory))
     {
         CurrentSessionContext.Bind(_sessionFactory.OpenSession());
     }
 }
Пример #12
0
 /// <summary>
 /// 将当前的Session工厂从当前上下文中取消绑定
 /// </summary>
 private void UnBindContext()
 {
     if (CurrentSessionContext.HasBind(this.SessionFactory))
     {
         CurrentSessionContext.Unbind(this.SessionFactory);
     }
 }
Пример #13
0
 //Aloca uma sessão do NHibernate no contexto da aplicação
 public void BindSession()
 {
     if (!CurrentSessionContext.HasBind(_sessionFactory.GetSessionFactory()))
     {
         CurrentSessionContext.Bind(_sessionFactory.OpenSession());
     }
 }
Пример #14
0
        public static ISession InitSession()
        {
            var context = HttpContext.Current;

            if (context != null)
            {
                var session = context.Items[SessionKey] as ISession;
                if (session == null)
                {
                    session = CreateSession();
                    context.Items[SessionKey] = session;
                }

                return(session);
            }
            else
            {
                if (!CurrentSessionContext.HasBind(Factory))
                {
                    var newSession = CreateSession();
                    CurrentSessionContext.Bind(newSession);
                }

                var session = GetCurrentSession();
                return(session);
            }
        }
Пример #15
0
        public override async Task SaveCurrentCheckpointAsync(string projectorIdentifier, int checkpoint)
        {
            var session = CurrentSessionContext.HasBind(sessionFactory) ?
                          sessionFactory.GetCurrentSession() :
                          sessionFactory.OpenSession();

            var checkpointInfo = await session.GetAsync <TCheckpointInfo>(projectorIdentifier);

            if (checkpointInfo == null)
            {
                checkpointInfo = new TCheckpointInfo
                {
                    StateModel       = projectorIdentifier,
                    CheckpointNumber = checkpoint
                };

                session.Save(checkpointInfo);
            }
            else
            {
                checkpointInfo.CheckpointNumber = checkpoint;

                session.Update(checkpointInfo);
            }

            // session.Flush();

            if (!CurrentSessionContext.HasBind(sessionFactory))
            {
                await session.FlushAsync();

                session.Dispose();
            }
        }
Пример #16
0
        public void Dispose()
        {
            if (!CurrentSessionContext.HasBind(_sessionFactory))
            {
                throw new InvalidOperationException("Invalid current session");
            }

            ISession session = _sessionFactory.GetCurrentSession();

            CurrentSessionContext.Unbind(_sessionFactory);

            if (!session.IsOpen)
            {
                throw new InvalidOperationException("Session closed before disposing context");
            }

            if (null != session.Transaction && session.Transaction.IsActive)
            {
                if (session.Transaction.WasCommitted == false && session.Transaction.WasRolledBack == false)
                {
                    session.Transaction.Rollback();
                }
            }

            session.Close();
        }
Пример #17
0
        /// <summary>
        /// Retursn the NHibernate session to use
        /// </summary>
        /// <returns></returns>
        internal ISession GetNHibernateSession(bool isReadonly, bool forceNewUnbounded = false)
        {
            //if a session has been supplied via the constructor (i.e. for testing)
            if (SingleProvidedSession != null)
            {
                if (!IsSingleSessionFinalized)
                {
                    using (new WriteLockDisposable(Locker))
                    {
                        IsSingleSessionFinalized = true;
                        //add the session to the finalizer
                        FrameworkContext.ScopedFinalizer.AddFinalizerToScope(SingleProvidedSession, x => UnbindAndCloseSession(NhSessionFactory));
                    }
                }


                EnsureFlushMode(SingleProvidedSession as ISessionImplementor, isReadonly);

                return(CheckFirstRunTasks(SingleProvidedSession));
            }


            // See http://nhforge.org/doc/nh/en/index.html#architecture-current-session
            // for details on contextual sessions

            var sessionFactory = GetNHibernateSessionFactory();

            if (!forceNewUnbounded)
            {
                //if we have a session factory, then check if its bound
                if (sessionFactory != null && CurrentSessionContext.HasBind(sessionFactory))
                {
                    LogHelper.TraceIfEnabled <EntityRepositoryFactory>("GetNHibernateSession: using ISessionFactory.GetCurrentSession()");
                    var boundSession = NhSessionFactory.GetCurrentSession();

                    EnsureFlushMode(boundSession as ISessionImplementor, isReadonly);

                    return(CheckFirstRunTasks(boundSession));
                }
            }

            LogHelper.TraceIfEnabled <EntityRepositoryFactory>("GetNHibernateSession: using ISessionFactory.OpenSession()");

            var sessionToReturn = NhSessionFactory.OpenSession();

            EnsureFlushMode(sessionToReturn as ISessionImplementor, isReadonly);

            //add the new session to the finalizer
            FrameworkContext.ScopedFinalizer.AddFinalizerToScope(sessionToReturn, x => UnbindAndCloseSession(NhSessionFactory));

            if (!forceNewUnbounded)
            {
                //dont bind the session if we're forcing new for nested transactions
                CurrentSessionContext.Bind(sessionToReturn);
            }


            return(CheckFirstRunTasks(sessionToReturn));
        }
Пример #18
0
 //Several functions omitted for brevity
 public static ISession GetCurrentSession()
 {
     if (!CurrentSessionContext.HasBind(GetSessionFactory()))
     {
         CurrentSessionContext.Bind(GetSessionFactory().OpenSession());
     }
     return(GetSessionFactory().GetCurrentSession());
 }
Пример #19
0
 public ISession GetCurrentSession()
 {
     if (!CurrentSessionContext.HasBind(SessionFactory))
     {
         CurrentSessionContext.Bind(SessionFactory.OpenSession());
     }
     return(SessionFactory.GetCurrentSession());
 }
Пример #20
0
 private void OpenSession()
 {
     if (!CurrentSessionContext.HasBind(_sessionFactory))
     {
         var session = _sessionFactory.OpenSession();
         CurrentSessionContext.Bind(session);
     }
 }
Пример #21
0
 public static void Bind()
 {
     if (!CurrentSessionContext.HasBind(Global.SessionFactory))
     {
         var sess = Global.SessionFactory.OpenSession();
         CurrentSessionContext.Bind(sess);
     }
 }
Пример #22
0
 /// <summary>
 /// Closes the session.
 /// </summary>
 public static void CloseSession()
 {
     if (Factory != null && CurrentSessionContext.HasBind(Factory))
     {
         var session = CurrentSessionContext.Unbind(Factory);
         session.Close();
     }
 }
Пример #23
0
 public void Complete()
 {
     if (CurrentSessionContext.HasBind(_sessionFactory))
     {
         var session = _sessionFactory.GetCurrentSession();
         session.Flush();
     }
 }
Пример #24
0
		private static ISession GetCurrentSession()
		{
			if (!CurrentSessionContext.HasBind(_sessionFactory))
			{
				CurrentSessionContext.Bind(_sessionFactory.OpenSession());
			}

			return _sessionFactory.GetCurrentSession();
		}
Пример #25
0
 /// <summary>
 /// Desbindea la sesion de la factory
 /// </summary>
 public void CloseSession()
 {
     // -- Si esta bindeada
     if (CurrentSessionContext.HasBind(SessionFactory))
     {
         // -- Desbindea
         CurrentSessionContext.Unbind(SessionFactory).Dispose();
     }
 }
Пример #26
0
 public void BindContext()
 {
     if (!CurrentSessionContext.HasBind(_sessionFactory))
     {
         var session = GetCurrentSession();
         session.BeginTransaction();
         CurrentSessionContext.Bind(session);
     }
 }
Пример #27
0
 public void UnBindContext()
 {
     if (CurrentSessionContext.HasBind(_sessionFactory))
     {
         Commit();
         Close();
         CurrentSessionContext.Unbind(_sessionFactory);
     }
 }
Пример #28
0
 public IQueryable <T> Query <T>()
     where T : DomainObject
 {
     if (!CurrentSessionContext.HasBind(_sessionFactory))
     {
         throw new InvalidOperationException("Unit of work should be started to query database");
     }
     return(_sessionFactory.GetCurrentSession().Query <T>());
 }
Пример #29
0
        public void BindSession()
        {
            if (CurrentSessionContext.HasBind(SessionFactory))
            {
                return;
            }

            CurrentSessionContext.Bind(OpenSession());
        }
Пример #30
0
        /// <summary> Get session
        /// </summary>
        /// <returns>current session</returns>
        /// <exception cref="System.NotImplementedException">
        /// Not found implementation of <see cref="Itb.DalCore.NHibernate.INHibernateInitializer"/> in Spring.NET config.
        /// Not found implementation of <see cref="Itb.DalCore.NHibernate.Mappings.INHibernateMappingsFinderEnumerator"/> in Spring.NET config.
        /// </exception>
        /// <exception cref="System.InvalidOperationException">
        /// Session does not bind to context
        /// </exception>
        public static ISession GetSession()
        {
            if (CurrentSessionContext.HasBind(SessionFactory))
            {
                return(SessionFactory.GetCurrentSession());
            }
            throw new InvalidOperationException(@"Database access logic cannot be used, if session not opened.
Implicitly session usage not allowed now. Please open session explicitly through IUnitOfWorkFactory.Create method");
        }