Skip to content

Instantly share code, notes, and snippets.

@lars-berger
Last active September 8, 2021 17:20
Show Gist options
  • Save lars-berger/f16f504938c592432be0f996b8fd9cfa to your computer and use it in GitHub Desktop.
Save lars-berger/f16f504938c592432be0f996b8fd9cfa to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
namespace MyProgram
{
public class Command
{
}
public class FocusCommand : Command
{
}
public interface ICommandHandler<TCommand> where TCommand : Command
{
void Handle(TCommand command);
}
public class FocusHandler : ICommandHandler<FocusCommand>
{
public void Handle(FocusCommand command)
{
Debug.WriteLine("FocusHandler was called.");
}
}
public class Bus
{
// Sends command to appropriate command handler.
public void Invoke<T>(T command) where T : Command
{
object handlerInstance = GetHandlerInstanceForCommand(command);
(handlerInstance as ICommandHandler<T>).Handle(command); // <--- Error is thrown here in 2nd case.
}
// Returns an instance of the corresponding handler for a command. In the real
// application, this gets the handler instance from the DI framework using
// `Provider.GetRequiredService`, which always returns an `object`.
private object GetHandlerInstanceForCommand<T>(T command) where T : Command
{
if (command.GetType() == typeof(FocusCommand))
return new FocusHandler();
else
throw new Exception();
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Debug.WriteLine("Application started");
Bus bus = new Bus();
bus.Invoke<FocusCommand>(new FocusCommand()); // Is called successfully.
Command parsedCommand = ParseCommand("FocusCommand");
bus.Invoke<Command>(parsedCommand); // Throws error.
}
// Returns different `Command` types based on input.
private static Command ParseCommand(string input)
{
if (input == "FocusCommand")
return new FocusCommand();
else
throw new Exception();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment