title: Simpleinjector: Is this the right way to RegisterManyForOpenGeneric when I have 2 implementations and want to pick one?
body: <p>Using simple injector <a href="https://cuttingedge.it/blogs/steven/pivot/entry.php?id=91" rel="nofollow">with the command pattern described here</a> and <a href="https://cuttingedge.it/blogs/steven/pivot/entry.php?id=92" rel="nofollow">the query pattern described here</a>. For one of the commands, I have 2 handler implementations. The first is a "normal" implementation that executes synchronously:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class SendEmailMessageHandler
      : IHandleCommands&lt;SendEmailMessageCommand&gt;
  {
      public SendEmailMessageHandler(IProcessQueries queryProcessor
          , ISendMail mailSender
          , ICommandEntities entities
          , IUnitOfWork unitOfWork
          , ILogExceptions exceptionLogger)
      {
          // save constructor args to private readonly fields
      }
  
      public void Handle(SendEmailMessageCommand command)
      {
          var emailMessageEntity = GetThisFromQueryProcessor(command);
          var mailMessage = ConvertEntityToMailMessage(emailMessageEntity);
          _mailSender.Send(mailMessage);
          emailMessageEntity.SentOnUtc = DateTime.UtcNow;
          _entities.Update(emailMessageEntity);
          _unitOfWork.SaveChanges();
      }
  }
  </code></pre>
  
  <p>The other is like a command decorator, but explicitly wraps the previous class  to execute the command in a separate thread:</p>
  
  <pre class="lang-cs prettyprint-override"><code>public class SendAsyncEmailMessageHandler 
      : IHandleCommands&lt;SendEmailMessageCommand&gt;
  {
      public SendAsyncEmailMessageHandler(ISendMail mailSender, 
          ILogExceptions exceptionLogger)
      {
          // save constructor args to private readonly fields
      }
  
      public void Handle(SendEmailMessageCommand command)
      {
          var program = new SendAsyncEmailMessageProgram
              (command, _mailSender, _exceptionLogger);
          var thread = new Thread(program.Launch);
          thread.Start();
      }
  
      private class SendAsyncEmailMessageProgram
      {
          internal SendAsyncEmailMessageProgram(
              SendEmailMessageCommand command
              , ISendMail mailSender
              , ILogExceptions exceptionLogger)
          {
              // save constructor args to private readonly fields
          }
  
          internal void Launch()
          {
              // get new instances of DbContext and query processor
              var uow = MyServiceLocator.Current.GetService&lt;IUnitOfWork&gt;();
              var qp = MyServiceLocator.Current.GetService&lt;IProcessQueries&gt;();
              var handler = new SendEmailMessageHandler(qp, _mailSender, 
                  uow as ICommandEntities, uow, _exceptionLogger);
              handler.Handle(_command);
          }
      }
  }
  </code></pre>
  
  <p>For a while simpleinjector was yelling at me, telling me that it found 2 implementations of <code>IHandleCommands&lt;SendEmailMessageCommand&gt;</code>. I found that the following works, but not sure whether it is the best / optimal way. I want to explicitly register this one interface to use the Async implementation:</p>
  
  <pre class="lang-cs prettyprint-override"><code>container.RegisterManyForOpenGeneric(typeof(IHandleCommands&lt;&gt;), 
      (type, implementations) =&gt;
      {
          // register the async email handler
          if (type == typeof(IHandleCommands&lt;SendEmailMessageCommand&gt;))
              container.Register(type, implementations
                  .Single(i =&gt; i == typeof(SendAsyncEmailMessageHandler)));
  
          else if (implementations.Length &lt; 1)
              throw new InvalidOperationException(string.Format(
                  "No implementations were found for type '{0}'.",
                      type.Name));
          else if (implementations.Length &gt; 1)
              throw new InvalidOperationException(string.Format(
                  "{1} implementations were found for type '{0}'.",
                      type.Name, implementations.Length));
  
          // register a single implementation (default behavior)
          else
              container.Register(type, implementations.Single());
  
      }, assemblies);
  </code></pre>
  
  <p><strong>My question: is this the right way, or is there something better?</strong> For example, I'd like to reuse the existing exceptions thrown by Simpleinjector for all other implementations instead of having to throw them explicitly in the callback. </p>
  
  <p><strong>Update reply to Steven's answer</strong></p>
  
  <p>I have updated my question to be more explicit. The reason I have implemented it this way is because as part of the operation, the command updates a <code>System.Nullable&lt;DateTime&gt;</code> property called <code>SentOnUtc</code> on a db entity after the <code>MailMessage</code> is successfully sent. </p>
  
  <p>The <code>ICommandEntities</code> and <code>IUnitOfWork</code> are both implemented by an entity framework <code>DbContext</code> class.The <code>DbContext</code> is registered per http context, using <a href="https://simpleinjector.codeplex.com/wikipage?title=PerWebRequestExtensionMethod" rel="nofollow">the method described here</a>:</p>
  
  <pre class="lang-cs prettyprint-override"><code>container.RegisterPerWebRequest&lt;MyDbContext&gt;();
  container.Register&lt;IUnitOfWork&gt;(container.GetInstance&lt;MyDbContext&gt;);
  container.Register&lt;IQueryEntities&gt;(container.GetInstance&lt;MyDbContext&gt;);
  container.Register&lt;ICommandEntities&gt;(container.GetInstance&lt;MyDbContext&gt;);
  </code></pre>
  
  <p>The default behavior of the <code>RegisterPerWebRequest</code> extension method in the simpleinjector wiki is to register a transient instance when the <code>HttpContext</code> is null (which it will be in the newly launched thread). </p>
  
  <pre class="lang-cs prettyprint-override"><code>var context = HttpContext.Current;
  if (context == null)
  {
      // No HttpContext: Let's create a transient object.
      return _instanceCreator();
  ...
  </code></pre>
  
  <p>This is why the Launch method uses the service locator pattern to get a single instance of <code>DbContext</code>, then passes it directly to the synchronous command handler constructor. In order for the <code>_entities.Update(emailMessageEntity)</code> and <code>_unitOfWork.SaveChanges()</code> lines to work, both must be using the same DbContext instance.</p>
  
  <p><strong>NOTE: Ideally, sending the email should be handled by a separate polling worker.</strong> This command is basically a queue clearing house. The EmailMessage entities in the db already have all of the information needed to send the email. This command just grabs an unsent one from the database, sends it, then records the DateTime of the action. Such a command could be executed by polling from a different process / app, but I will not accept such an answer for this question. For now, we need to kick off this command when some kind of http request event triggers it.</p>