title: Create Instance of Generic
body: <p>I have a WCF service that implements a command pattern.  Using reflection, I've created a Dictionary where the key is the command type and the value is the CommandHandler.  The idea is to receive the command from WCF, using the dictionary to get the handler type, then create an instance of the handler using the activator.</p>
  
  <pre><code>    public CommandResponse RunCommand(Command command)
      {
          _logger.Trace("Running Command");
          var handlerType = HandlerMap[command.GetType()];
  
          var handler = (AbstractCommandHandler&lt;&gt;)Activator.CreateInstance(handlerType);
  
          handler.HandleCommand(command);
          return new PostStatCommandResponse();
  
      }
  
  public class StatCommandHandler : AbstractCommandHandler&lt;PostStatCommand&gt;
  {
  
      public override void HandleCommand(PostStatCommand command)
      {
  
      }
  }
  </code></pre>
  
  <p>The problem is that Activator.CreateInstance returns an object, not a strongly typed commandhandler.  I need to be able to call the HandleCommand, but can't figure out how to cast it to the base AbstractCommandHandler&lt;></p>
  
  <pre><code>// Syntax error.  Gotta provide type to generic
  (AbstractCommandHandler&lt;&gt;)Activator.CreateInstance(handlerType);
  
  // Casting error at run time
  (AbstractCommandHandler&lt;Command&gt;)Activator.CreateInstance(handlerType);
  
  // This is dumb and defeats the purpose.
  (AbstractCommandHandler&lt;PostStatCommand&gt;)Activator.CreateInstance(handlerType);
  </code></pre>
  
  <p>Help?</p>