Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8124765
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T06:34:20+00:00 2026-06-06T06:34:20+00:00

I use NHiberante at my win service. Sometimes I get System.ObjectDisposedException: Session is closed!

  • 0

I use NHiberante at my win service. Sometimes I get

System.ObjectDisposedException: Session is closed!
Object name: 'ISession'.
   at NHibernate.Impl.AbstractSessionImpl.ErrorIfClosed()
   at NHibernate.Impl.AbstractSessionImpl.CheckAndUpdateSessionStatus()
   at NHibernate.Impl.SessionImpl.FireSave(SaveOrUpdateEvent event)
   at NHibernate.Impl.SessionImpl.Save(Object obj)
   at Attraction.DAL.Repositories.Repository`1.Save(T entity)
   at Attraction.VideoDispatcher.Program.ThreadPoolCallback(Object threadContext)

I have no idea what’s wrong.
My session management subsystem:

Repository:

 public class Repository<T> : IRepository<T>, IDisposable
    {
        protected readonly bool CommitAtDispose;
        public Repository(bool commitAtDispose)
        {
            CommitAtDispose = commitAtDispose;
            StartSession();
        }
        private void StartSession()
        {
            if (NHibernateSession == null)
                NHibernateHelper.StartSession();
        }
        public void Dispose()
        {
            if (CommitAtDispose)
                Flush();
        }
        public void Flush()
        {
            NHibernateHelper.EndSession();
        }
        protected override sealed ISession NHibernateSession
        {
            get
            {
                return SessionManager.CurrentSession; 
            }
        }       
        public virtual T GetById(int id)       
        public virtual List<T> GetAll()        
        public virtual List<T> GetByPage(int pageIndex, int pageSize)       
        public virtual int GetCount()        
        public virtual List<T> GetByCriteria(params ICriterion[] criterion)       
        public virtual T Save(T entity)       
        public virtual T Update(T entity)        
        public virtual void Delete(T entity)        
    }
}

SessionManager – singletone for provide access to sessionfactory

public class SessionManager : ISessionFactoryProvider
{
        private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private readonly ISessionFactory sessionFactory;
        public static ISessionFactory SessionFactory
        {
            get { return Instance.sessionFactory; }
        }
        public ISessionFactory GetSessionFactory()
        {
            return sessionFactory;
        }
        public static ISession OpenSession()
        {
            return Instance.GetSessionFactory().OpenSession();
        }
        public static ISession CurrentSession
        {
            get
            {
                if (!CurrentSessionContext.HasBind(Instance.GetSessionFactory()))
                    return null;
                return Instance.GetSessionFactory().GetCurrentSession();
            }
        }


        public static SessionManager Instance
        {
            get
            {
                return NestedSessionManager.sessionManager;
            }
        }
        private SessionManager()
        {
            Log.Info("Start creating factory");
            Configuration configuration = new Configuration().Configure();
            sessionFactory = configuration.BuildSessionFactory();
            Log.Info("End creating factory");

        }

        class NestedSessionManager
        {
            internal static readonly SessionManager sessionManager =
                new SessionManager();
        }
    }

NhibernateHelper, which do some work for start and end session:

public static class NHibernateHelper
    {
        public static void StartSession()
        {
            var session = SessionManager.SessionFactory.OpenSession();
            session.BeginTransaction();
            CurrentSessionContext.Bind(session);

        }
        public static void EndSession()
        {
            var session = SessionManager.CurrentSession;
            CurrentSessionContext.Unbind(SessionManager.SessionFactory);
            if (session != null)
            {
                try
                {
                    if (session.Transaction != null && session.Transaction.IsActive)
                        session.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    session.Transaction.Rollback();
                    throw new ApplicationException("Error committing database transaction. "+ex.Message, ex);
                }
                finally
                {
                    session.Close();
                    session.Dispose();

                }
            }


        }
    }

May be my design isn’t so good, but I couldn’t imagine how can I catch this error.

UPD

Sorry my config. I haven’t migrate to fluent yet so:

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="dialect">NHibernate.Dialect.MySQLDialect</property>
      <property name="connection.driver_class">NHibernate.Driver.MySqlDataDriver</property>
      <property name="connection.connection_string">***</property>
      <property name="show_sql">false</property>
      <property name="default_schema">**_***</property>
      <property name="current_session_context_class">thread_static</property>
      <mapping assembly="***.Core"/>
    </session-factory>
  </hibernate-configuration>

UPD2

Save method:

        public virtual T Save(T entity)
        {
            NHibernateSession.Save(entity);
            return entity;
        }

Threadpool callback:

        public static void DetectStart(Object threadContext)
        {
            try
            {
                var task = (TasksPerAttraction)threadContext;                
                var startInfo = new ProcessStartInfo(..., ...)
                {
                    UseShellExecute = false,
                    RedirectStandardOutput = true
                };
                Process p = Process.Start(startInfo);
                var outputXml = p.StandardOutput.ReadToEnd();
                p.WaitForExit();
                var doc = XDocument.Parse(outputXml);
                foreach (var xElement in doc.Root.Descendants("start"))
                {
                    var startDetection = new StartDetection
                                             {
                                                 DtStart = DateTime.Parse(xElement.Attribute("startTime").Value),
                                                 Attraction = task.Attraction,                                                
                                             };
                    lock (spinLock)
                    {
                        using (var repo = new Repository<StartDetection>(true))
                            repo.Save(startDetection);
                    }
                }
                var tskRepo = new Repository<Task>(true);
                foreach(var tsk in task.Tasks)
                {
                    tsk.IsProcessedStart = true;
                    tskRepo.Update(tsk);
                }
                tskRepo.Flush();
            }
            catch (Exception ex)
            {
                //....
            }
        }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T06:34:22+00:00Added an answer on June 6, 2026 at 6:34 am

    There are a few potential issues, but I suspect the biggest issue is that you are saving the task.Attraction in one session (so the Attraction for that task is associated to session 1), and then saving the tasks in another session – so you end up with the Attraction in session 1, which is now closed, and session 2 is navigating the relationships to see if it needs to save the Attraction and hence the error. This is a bit of an assumption since I don’t have your model or mapping.

    I think the easiest fix would be to open the session in your callback, ie:

    public static void DetectStart(Object threadContext)
    {
        try
        {
            ... run your process ...
            p.WaitForExit();
            // **** OPEN SESSION HERE ****
            NHibernateHelper.StartSession(); 
    
            var doc = XDocument.Parse(outputXml);
            foreach (var xElement in doc.Root.Descendants("start"))
            {
                var startDetection = new StartDetection
                                         {
                                             DtStart = DateTime.Parse(xElement.Attribute("startTime").Value),
                                             Attraction = task.Attraction,                                                
                                         };
                lock (spinLock)
                {
                    // *** DON'T CLOSE THE SESSION ON DISPOSE
                    using (var repo = new Repository<StartDetection>(false)) 
                        repo.Save(startDetection);
                }
            }
            // *** DON'T CLOSE THE SESSION ON DISPOSE HERE EITHER!
            using(var tskRepo = new Repository<Task>(false)) 
            { 
                foreach(var tsk in task.Tasks)
                {
                    tsk.IsProcessedStart = true;
                    tskRepo.Update(tsk);
                }
                tskRepo.Flush();
            }
        }
        catch (Exception ex)
        {
            //....
        }
        finally {
            // *** MAKE SURE YOU CLOSE THE SESSION
            NHibernateHelper.EndSession();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We want to use NHibernate behind our WCF service but we are having problems
I use NHibernate (2.0.1GA) with my project. At runtime I get the Invalid Cast
I'm trying to use nHibernate, Spring and WCF together. I've got an Order object,
Here is my basic situation. I'm trying to use NHibernate to get information from
I have 2 classes named Order and Orderrow. I use NHibernate to get a
I want to upgrade my application to use NHiberante 3 instead of NHibernate 2.1.2
Application use NHibernate. I Have object A that contains set of objects B. I
We use NHibernate as our ORM. For the retrieval of most instances session.Query<T>() is
I want to use nHibernate in a windows service. If the systems boots, it
I'm converting a legacy system's data layer to use NHibernate. The old db is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.