RavenDB Session Management with NServiceBus

time to read 2 min | 266 words

I got a few questions about this in the past, and I thought that I might as well just post how I recommend deal with RavenDB session management for NServiceBus:

public class RavenSessionMessageModule : IMessageModule
{
  ThreadLocal<IDocumentSession> currentSession = new ThreadLocal<IDocumentSession>();

  IDocumentStore store;
  
  public RavenSessionMessageModule(IDocumentStore store)
  {
    this.store = store;
  }

  public IDocumentSession CurrentSession
  {
    get{ return currentSession.Value; }
  }

  public void HandleBeginMessage()
  {
    currentSession.Value = store.OpenSession();
  }
  
  public void HandleEndMessage()
  {
    using(var old = currentSession.Value)
    {
      currentSession.Value = null;
      old.SaveChanges();
    }
  }
  
  public void HandleError()
  {
    using(var old = currentSession.Value)
      currentSession.Value = null;
  }
}

When any of your message handlers needs to get the session, you need to wire the container in such a way that it would provide the RavenSessionMessageModule.CurrentSession to it.