I have got a interface ICommandHandler<TCommand> where TCommand is of type ICommand (another interface). SomeWorkProcessCommandHandler class implements ICommandHandler.
What i'm unable to do is pass the SomeWorkProcessCommandHandler class to another class where it expects ICommandHandler in its constructor
In the below code Manager class expects ICommandHandler<TCommand> in its constructor. I'm getting compile time error when i pass someWorkProcessCommandHandler object. If i cast it i get run time exception.
How do i pass someWorkProcessCommandHandler object in the constructor?
Please don't tell me to remove it from the constructor and figure out the handler in the Execute method. I'm not trying to do that. The only thing i'm trying to figure here is, how to pass objects that have hierarchy interface
public interface ICommand
{
}
public interface ICommandHandler<TCommand> where TCommand : ICommand
{
void Handle(TCommand command);
}
public class SomeWorkProcessCommand : ICommand
{
}
public class SomeWorkProcessCommandHandler : ICommandHandler<SomeWorkProcessCommand>
{
public void Handle(SomeWorkProcessCommand command)
{
Console.WriteLine("Some work Process Command Handler ");
}
}
public class Manager
{
private readonly ICommandHandler<ICommand> handler;
public Manager(ICommandHandler<ICommand> handler)
{
this.handler = handler;
}
public void Execute(ICommand command)
{
handler.Handle(command);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var someWorkProcessCommandHandler = new SomeWorkProcessCommandHandler();
someWorkProcessCommandHandler.Handle(new SomeWorkProcessCommand());// This line works fine if the below code is not present
//var manager = new Manager(someWorkProcessCommandHandler); //Compile time error
var manager = new Manager((ICommandHandler<ICommand>)someWorkProcessCommandHandler); //Runtime error after casting
manager.Execute(new SomeWorkProcessCommand());
Console.ReadKey();
}
}