Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Basic implementation of a command register
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((T)cmd);
};
Handlers.Add(typeof(T), action);
}
}
class Dispatcher
{
CommandRegister register;
public Dispatcher(CommandRegister register)
{
this.register = register;
}
public void Send<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