Question

Is there anyway to verify if a Session has been disposed of by NHibernate?

I have a wrapper class on Session that has it's own Finalizer and IDispoable implementation however if the Session gets disposed before I handle it myself in my class I end up receiving an ObjectDisposedException.

I really don't wish to wrap my clean up code with

try {
...
}
catch (ObjectDisposedException) { }

But I'm not really sure of any other way. The Session.IsOpen and Session.IsActive properties do not seem to offer any reliable information for me to acknowledge the session has been disposed of.

For full source you can view it on Assembla.

Was it helpful?

Solution

Ok, just taked a peek at your code. I don't know if this is exactly the issue, but you are calling End() from the conversation dispose method, which in turn tries to reconnect and disposes the session.. if you have eplicitly called End() before this you will get what you get, avoid that call. I think you shouldn't worry about rolling back the transaction before the session dispose as this is implicitly done. Just taken a quick look, but i think i really like your implementation.

OTHER TIPS

I always thought best practice with NHibernate was "session per request" meaning that it should only live inside the 'using' scope.

using(Session session = new Session())
{
}

I'd suggest trying to prevent two people from disposing the session/conversation. If you control the creation of sessions you could wrap it in your own ISession impl that performs it's own IsAlreadyDisposed() check to prevent the exception. Still, considering that effort vs "expected exception" and the original code doesn't look so bad.

I'd also suggest watching out with your finaliser implementation. The "Session.Is().InTransaction()" goes Session->Transaction and the session might be null by the time the finaliser gets round to it. Navigating a managed relationship at finaliser time isn't guaranteed to work.

"That's one of the most absurd things I've seen to have it's Open property remain true even after disposal"

Why would an object you already have disposed contain reliable information about it's state?. You shouldn't try to use a disposed session, i don't know where nhibernate is disposing your session either, are you sure you are not disposing it yourself?.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top