What is difference between session.Close()
and session.Dispose()
?
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.
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With