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.
public CommandResponse RunCommand(Command command)
{
_logger.Trace("Running Command");
var handlerType = HandlerMap[command.GetType()];
var handler = (AbstractCommandHandler<>)Activator.CreateInstance(handlerType);
handler.HandleCommand(command);
return new PostStatCommandResponse();
}
public class StatCommandHandler : AbstractCommandHandler<PostStatCommand>
{
public override void HandleCommand(PostStatCommand command)
{
}
}
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<>
// Syntax error. Gotta provide type to generic
(AbstractCommandHandler<>)Activator.CreateInstance(handlerType);
// Casting error at run time
(AbstractCommandHandler<Command>)Activator.CreateInstance(handlerType);
// This is dumb and defeats the purpose.
(AbstractCommandHandler<PostStatCommand>)Activator.CreateInstance(handlerType);
Help?
CreateInstance<T>()instead ofCreateInstance(Type)?