Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between session.Close() and session.Dispose()

Tags:

nhibernate

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

like image 525
Andy Avatar asked Jan 19 '11 20:01

Andy


3 Answers

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.

like image 148
Sly Avatar answered Oct 22 '22 23:10

Sly


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().

like image 22
Justin Niessner Avatar answered Oct 22 '22 22:10

Justin Niessner


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.

like image 32
jrequejo Avatar answered Oct 22 '22 23:10

jrequejo