NServiceBus keeps a static pool of threads that process incoming messages. This means that threads are not recreated for each new message with the effect that thread static variables are not cleared.

If you use the thread static cache lifecycle of [Name of your favorite container here] this will have the effect that the objects placed in this cache will not be recreated for each new message as you might expect. The thread static cache is a great way to store objects that should be shared for the duration of each request. One example would be to share the NHibernate session as I have talked about earlier.

To remedy this problem for my favorite container StructureMap we need to extend the built-in thread static lifecycle and connect it to the message module feature of NServiceBus in order to clear the cache when message processing is complete.
Our new lifecycle looks like this:
   public class NServiceBusThreadLocalStorageLifestyle : ThreadLocalStorageLifecycle,  IMessageModule   {       public void HandleBeginMessage(){}

       public void HandleEndMessage()       {           EjectAll();       }

       public void HandleError(){}   }
To use our new lifecycle we'd have to configure StructureMap with the following syntax:
x.For<ISession>()  .LifecycleIs(new NServiceBusThreadLocalStorageLifestyle())  .Use(ctx =>ctx.GetInstance<ISessionFactory>().OpenSession()));

The code for my NHibernate sample project has been updated to reflect this.

Happy caching!