16

What is difference between session.Close() and session.Dispose()?

3 Answers 3

24

From the Nhibernate Source code:

private void Dispose(bool isDisposing)
{
    using (new SessionIdLoggingContext(base.SessionId))
    {
        if (!base.IsAlreadyDisposed)
        {
            log.Debug(string.Format("[session-id={0}] executing real Dispose({1})", base.SessionId, isDisposing));
            if (!(!isDisposing || base.IsClosed))
            {
                this.Close();
            }
            base.IsAlreadyDisposed = true;
            GC.SuppressFinalize(this);
        }
    }
}

So Dispose method calls Close(). Calling either Close() or Dispose() methods will close the Session not allowing you to work with it anymore.

11

Calling session.Close() will close the session but not dispose of the object.

Calling session.Dispose() (usually through the use of a using block) will close the session if it is open as well as perform the extra operations of Dispose().

2

This question is a few years old now but it still shows up in top results through search engines so I thought I'd still be worth adding a comment. Also, I'm using NHibernate 5.1.1 so maybe this is something that has changed since the questions was originally posted.

That out of the way, turns out that if you call session.Close() within a TransactionScope, you will get a System.Transactions.TransactionAbortedException. If you take a look at the Close() method remarks inside SessionImpl you will find this:

/// /// Do not call this method inside a transaction scope, use Dispose instead, since /// Close() is not aware of distributed transactions ///

So at least within the context of a TransactionScope, Close() must be avoided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.