Skip to content

Instantly share code, notes, and snippets.

@gregoryyoung
Created November 27, 2013 15:33
Show Gist options
  • Save gregoryyoung/7677671 to your computer and use it in GitHub Desktop.
Save gregoryyoung/7677671 to your computer and use it in GitHub Desktop.
public class Dispatcher<TMessage, TResult>
{
private readonly Dictionary<Type, Func<TMessage, TResult>> _dictionary = new Dictionary<Type, Func<TMessage, TResult>>();
public void Register<T>(Func<T, TResult> func) where T : TMessage
{
_dictionary.Add(typeof(T), x => func((T)x));
}
public TResult Dispatch(TMessage m)
{
Func<TMessage, TResult> handler;
if (!_dictionary.TryGetValue(m.GetType(), out handler))
{
throw new Exception("cannot map " + m.GetType());
}
return handler(m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment