The interfaces,commands and command handler set up as per instructions in Simpleinjector wiki.
public interface ICommand
{
string Name { get; set; }
}
public class Command1 : ICommand
{
public string Name { get; set; }
}
public class Command2 : ICommand
{
public string Name { get; set; }
}
public interface ICommandHandler<TCommand>
{
void Execute(TCommand Command);
}
public class Command1Handler : ICommandHandler<Command1>
{
public void Execute(Command1 Command) {
Console.WriteLine(Command.Name);
}
}
public class Command2Handler : ICommandHandler<Command2>
{
public void Execute(Command2 Command) {
Console.WriteLine(Command.Name + "Hello");
}
}
Decorator:
public class CommandDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> _handler;
public CommandDecorator(ICommandHandler<TCommand> handler)
{
this._handler = handler;
}
public void Execute(TCommand command)
{
this._handler.Execute(command);
}
}
Sample program
public class Program
{
static void Main(string[] args)
{
Container container = new Container();
//registering
container.RegisterAll<ICommand>(typeof(Command1), typeof(Command2));
container.RegisterManyForOpenGeneric(
typeof(ICommandHandler<>),
typeof(ICommandHandler<>).Assembly);
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(CommandDecorator<>));
container.Verify();
// sample test command
ICommand testcommand = new Command2();
testcommand.Name = "command 1";
var type = typeof(ICommandHandler<>).MakeGenericType(testcommand.GetType());
dynamic instance = container.GetInstance(type);
instance.Execute((dynamic)testcommand);
}
}
Is this the right way to get the right handler for handling the command at runtime. This is a sample and in the real app the commands are going to posted to a queue and a service is going to read the command and process it . I guess the Decorator has to be used for that but am not able to get it working. please suggest better options if any.