Difference between CallSessionContext, ThreadLocalSessionContext and ThreadStaticSessionContext

nhibernate

From NHibernate documentation, it doesn't explain much.

What is the difference between those three ?

In what situation that one of those context is more preferable than the others ?

P.S. ThreadLocalSessionContext doesn't exist in the documentation, but it does exist in NHibernate dll.

Best Answer

It doesn't look like ThreadLocalSessionContext can currently be used. There is no configuration that supports it's use and it's only referenced within NHibernate by a unit test.

According to the code CallSessionContext is a way of handling sessions in .Net remoting see comments in code below for more detail. It looks like NHibernate basically stores the session in the remoting call context. More info about remoting call contexts can be found here

/// <summary>
/// Provides a <see cref="ISessionFactory.GetCurrentSession()">current session</see>
/// for each <see cref="System.Runtime.Remoting.Messaging.CallContext"/>.
/// Not recommended for .NET 2.0 web applications.

ThreadStaticSessionContext is used for handling sessions in multi-threaded applications. It uses a [ThreadStatic] attribute to declare the session such that there is a session per thread. I currently use this. See this SO link for a code example of how you would use it: What is the best NHibernate session management approach for using in a multithread windows service application?

Also in addition to this it looks like NHibernate is adding another session context in version 3.2 called WcfOperationSessionContext. Below is the description from the code:

/// <summary>
/// Provides a <see cref="ISessionFactory.GetCurrentSession()">current session</see>
/// for the current OperationContext in WCF. Works only during the lifetime of a WCF operation.
/// </summary>

To answer your 2nd question it really depends on what type of application you are implementing and how you are using your sessions. Hopefully between the nhibernate documentation and the descriptions above you'll have a better idea of what context you should use.

Related Topic