title: NHibernate Multithreaded Session Management
body: <p>I have a situation which involves several threads simultaneously populating a database with data scraped from web sources. The scrapers are to be run periodically to collect new data from various sources.</p>
  
  <p>I am new to using NHibernate and not entirely sure how best to manage sessions.</p>
  
  <p>An example of what each worker does:</p>
  
  <ul>
  <li>Scrape an entity A from a web source</li>
  <li>Scrape each entity B related to A, and record that A has another B (i.e. an A has many B, a B has one A)</li>
  </ul>
  
  <p>To persist each B, the session needs a reference to A to create the B with and then A needs to add B to its list of children. Both A and B are then persisted.</p>
  
  <p>There is a hierarchy of this kind of A-B child-parent situation such that A has many B, B has many C... At the leaf level, A has thousands of leaf children, so it is impractical(?) to keep the session open all the way down this chain.</p>
  
  <p>An alternative is recording the identifier of each parent down the chain (which can be stored independently of the session) and loading in the parent via this id each time a child needs to be created.</p>
  
  <p>I also understand that an <code>ISession</code> is meant to be single-threaded, so I will need at the very least one session per thread, but beyond this I'm really not sure of the best approach?</p>
  
  <p>Any ideas appreciated, bit confused at the moment!</p>