Skip to content

Instantly share code, notes, and snippets.

@yreynhout
Created May 21, 2015 13:48
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 yreynhout/0a0bc4e3514cd1a80ca6 to your computer and use it in GitHub Desktop.
Save yreynhout/0a0bc4e3514cd1a80ca6 to your computer and use it in GitHub Desktop.
public class EventRouter
{
private readonly Dictionary<Type, Action<object>> _handlers;
public EventRouter()
{
_handlers = new Dictionary<Type, Action<object>>();
}
public void Register<T>(Action<T> handler)
{
if (handler == null)
throw new ArgumentNullException("handler");
_handlers.Add(typeof(T), _ => handler((T)_));
}
public void Register(Type type, Action<object> handler)
{
if (type == null)
throw new ArgumentNullException("type");
if (handler == null)
throw new ArgumentNullException("handler");
_handlers.Add(type, handler);
}
public void Route(object @event)
{
if (@event == null)
throw new ArgumentNullException("event");
Action<object> handler;
if (_handlers.TryGetValue(@event.GetType(), out handler))
{
handler(@event);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment