title: NServiceBus, NHibernate and Multitenancy
body: <p>We're using NServiceBus to perform document processing for a number of tenants.</p>
  
  <p>Each tenant has their own database and we're using NHibernate for data access. In the web application we're using our IoC tool (StructureMap) to handle session management. Essentially we maintain a session factory for each tenant. We're able to identify the tenant from <code>HttpContext</code>.</p>
  
  <p>When we kick off document processing using NServiceBus we have access to the tenant identifier. We need this tenant id to be available throughout the processing of the document (we have 2 sagas and fire off a number of events). </p>
  
  <p>We would need to create a NHibernate <code>SessionFactory</code> for <em>each</em> tenant so would need some way of obtaining the tenant id when we configure StructureMap.</p>
  
  <p>I've seen a few posts suggesting to use a message header to store the tenant identifier but am unsure how to:</p>
  
  <ol>
  <li>Set a message header when we first submit a document (sending a <code>SubmitDocumentCommand</code>)</li>
  <li>Reference the header when we configure StructureMap</li>
  <li>Access the header within our sagas/handlers</li>
  <li>Ensure the header flows from one message to the next. When we send a <code>SubmitDocumentCommand</code> it is handled by the <code>DocumentSubmissionSaga</code>. If the submission succeeds we will send off a <code>DocumentSubmittedEvent</code>. We'd want to make sure the tenant id is available at all points in the process.</li>
  </ol>
  
  <p>I believe with this information I can successfully implement multitenancy with NHibernate but anything more specific to this scenario would be appreciated.</p>