I have commands to execute. Commands are plain C# classes with some data.
And I want to make command-specific handlers.
And finally, I want to loop through commands and call corresponding commandHandlers.
C# does not allow such usage, since ICommandHandler<> cannot be used without <>. How do we solve this problem?
Solution
Define ICommandHandler as command-type-agnostic.
Define CommandHandlerBase as generic class that accepts command-type T. It implements ICommandHandler, and it requires its child to implement abstract Execute(T command).
Now command handler looks like:
Note that Command1Handler’s Execute() receives Command1, not ICommand.
Bonus: Command1Handler does not worry about CanHandle(), since by declaring CommandHandlerBase<Command1> I already said I can handle Command1 only.