title: Mixed lifestyle for Per Thread and Per Web Request with Simple Injector
body: <p>I'm using <code>SimpleInjector</code> as my IoC library. I register <code>DbContext</code> as per web request and it works fine. But there is one task that I run it in a background thread. So, I have a problem to create <code>DbContext</code> instances. e.g.</p>
  
  <ol>
  <li><code>Service1</code> has an instance of <code>DbContext</code></li>
  <li><code>Service2</code> has an instance of <code>DbContext</code> </li>
  <li><code>Service1</code> and <code>Service2</code> run from background thread. </li>
  <li><code>Service1</code> fetches an entity and pass it to <code>Service2</code></li>
  <li><code>Service2</code> uses that entity, but entity is detached from <code>DbContext</code></li>
  </ol>
  
  <p>Actually the problem is here: <code>Service1.DbContext</code> is difference from <code>Service2.DbContext</code>.</p>
  
  <p>It seems when I run a task in a separate thread in ASP.NET MVC, <code>SimpleInjector</code> creates a new instance of <code>DbContext</code> for each call. While some IoC libraries (for example <code>StructureMap</code>) have a mixed lifestyle for per-thread-per-webrequest, it seems <code>SimpleInjector</code> hasn't one. Am I right?</p>
  
  <p>Have you any idea to solve this problem in <code>SimpleInjector</code>?
  Thanks in advance.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>My services are here:</p>
  
  <pre><code>class Service1 : IService1 {
      public Service1(MyDbContext context) { }
  }
  
  class Service2 : IService2 {
      public Service2(MyDbContext context, IService1 service1) { }
  }
  
  class SyncServiceUsage {
      public SyncServiceUsage(Service2 service2) {
          // use Service2 (and Service1 and DbContext) from HttpContext.Current
      }
  }
  
  class AsyncServiceUsage {
      public AsyncServiceUsage(Service2 service2) {
          // use Service2 (and Service1 and DbContext) from background thread
      }
  }
  
  public class AsyncCommandHandlerDecorator&lt;TCommand&gt; 
      : ICommandHandler&lt;TCommand&gt; where TCommand : ICommand {
  
      private readonly Func&lt;ICommandHandler&lt;TCommand&gt;&gt; _factory;
  
      public AsyncCommandHandlerDecorator(Func&lt;ICommandHandler&lt;TCommand&gt;&gt; factory) {
          _factory = factory;
      }
  
      public void Handle(TCommand command) {
          ThreadPool.QueueUserWorkItem(_ =&gt; {
              // Create new handler in this thread.
              var handler = _factory();
              handler.Handle(command);
          });
      }
  }
  
  void InitializeSimpleInjector() {
      register AsyncCommandHandlerDecorator for services (commands actually) that starts with "Async"
  }
  </code></pre>
  
  <p>I user <code>Service2</code> sometimes and <code>AsyncService2</code> other times. </p>