Over a million developers have joined DZone.

RavenDB Session Management with NServiceBus

· Database Zone

Build fast, scale big with MongoDB Atlas, a hosted service for the leading NoSQL database. Try it now! Brought to you in partnership with MongoDB.

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>();

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

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

  public void HandleBeingMessage()
  {
    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.

Now it's easier than ever to get started with MongoDB, the database that allows startups and enterprises alike to rapidly build planet-scale apps. Introducing MongoDB Atlas, the official hosted service for the database on AWS. Try it now! Brought to you in partnership with MongoDB.

Topics:

Published at DZone with permission of Ayende Rahien, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}