title: Managing RavenDb session in Windsor under NServiceBus
body: <p>I'm using NServiceBus (3.2.2), RavenDB (1.2.2017-Unstable) and Windsor (3.0.0.4001) in an MVC 4 project.</p>
  
  <p>I have a IHandleMessages class that handles 3 different messages, and that needs an IDocumentSession, and therefore defines a property such as:</p>
  
  <pre><code>public IDocumentSession DocumentSession { get; set; }
  </code></pre>
  
  <p>I've copied the RavenDbUnitOfWork implementation from NServiceBus' <a href="http://nservicebus.com/UnitOfWorkImplementationForRavenDB.aspx" rel="noreferrer">website</a></p>
  
  <p>I've registered IDocumentStore, IDocumentSession and IManageUnitsOfWork in my Windsor container as follow:</p>
  
  <pre><code>container.Register(
              Component
                  .For&lt;IManageUnitsOfWork&gt;()
                  .ImplementedBy&lt;RavenUnitOfWork&gt;()
                  .LifestyleTransient()
              );
  container.Register(
              Component
                  .For&lt;IDocumentStore&gt;()
                  .UsingFactoryMethod(k =&gt; DocumentStoreHolder.DocumentStore)
                  .LifestyleSingleton(),
              Component
                  .For&lt;IDocumentSession&gt;()
                  .UsingFactoryMethod(k =&gt; k.Resolve&lt;IDocumentStore&gt;().OpenSession())
                  .LifestyleTransient()
              );
  </code></pre>
  
  <p>NServiceBus is configured to use my container:</p>
  
  <pre><code>Configure.With()
           .CastleWindsorBuilder(container);
  </code></pre>
  
  <p>I'm encountering the problem that the UnitOfWork and the message handler receive different instances of the DocumentSession. This means that objects stored in the session in the message handler are not saved, since SaveChanges() is called on a different DocumentSession.</p>
  
  <p>Removing the Transient lifestyle causes different kind of problems, that result in concurrency/conflicts when updating objects from RavenDb, since (probably) the message handler keeps getting the same instance of the DocumentSession, which holds a cached version of the updated object.</p>
  
  <p><strong>Update:</strong></p>
  
  <p>As suggested, I've tried changing the registration of the IDocumentSession in Windsor, to the Scope lifestyle, like this:</p>
  
  <pre><code>Component
      .For&lt;IDocumentSession&gt;()
      .UsingFactoryMethod(k =&gt; k.Resolve&lt;IDocumentStore&gt;().OpenSession())
      .LifestyleScope()
  </code></pre>
  
  <p>This causes exceptions when the container tries to resolve the MVC Controller, saying that the scope was not found, and asking if I forgot to call BeginScope().</p>