Created
May 21, 2015 13:48
-
-
Save yreynhout/0a0bc4e3514cd1a80ca6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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