Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mat-mcloughlin
Created August 7, 2016 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mat-mcloughlin/4b9f73221d7ab1e7bd597a9b95da1b5b to your computer and use it in GitHub Desktop.
Save mat-mcloughlin/4b9f73221d7ab1e7bd597a9b95da1b5b to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var register = new CommandRegister();
register.Register<AdmitPatient>(cmd =>
{
Console.WriteLine($"FirstName: {cmd.FirstName}");
Console.WriteLine($"Surname: {cmd.Surname}");
});
var dispatcher = new Dispatcher(register);
dispatcher.Send(new AdmitPatient("Fredd", "Bloggs"));
}
class AdmitPatient
{
public string FirstName { get; }
public string Surname { get; }
public AdmitPatient(string firstName, string surname)
{
FirstName = firstName;
Surname = surname;
}
}
class CommandRegister
{
public Dictionary<Type, Action<object>> Handlers { get; }
public CommandRegister()
{
Handlers = new Dictionary<Type, Action<object>>();
}
public void Register<T>(Action<T> handler) where T : class
{
Action<object> action = cmd =>
{
handler(cmd as T);
};
Handlers.Add(typeof(T), action);
}
}
class Dispatcher
{
CommandRegister register;
public Dispatcher(CommandRegister register)
{
this.register = register;
}
public void Send(object message)
{
SendGeneric((dynamic)message);
}
void SendGeneric<T>(T command)
{
register.Handlers[typeof(T)](command);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment