Skip to content

Instantly share code, notes, and snippets.

@yevhen
Created November 27, 2013 20:17
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 yevhen/7682490 to your computer and use it in GitHub Desktop.
Save yevhen/7682490 to your computer and use it in GitHub Desktop.
Extended version of Dispatcher from Greg Young' post http://goodenoughsoftware.net/2013/11/27/how-to-use-partial-application-like-di/
public class Dispatcher
{
readonly Dictionary<Type, Func<object, object>> _dictionary = new Dictionary<Type, Func<object, object>>();
public void Register<TMessage, TResult>(Func<TMessage, TResult> func)
{
_dictionary.Add(typeof(TMessage), x => func((TMessage) x));
}
public void Register<TMessage>(Action<TMessage> act)
{
_dictionary.Add(typeof(TMessage), x =>
{
act((TMessage) x);
return null;
});
}
public TResult Dispatch<TMessage, TResult>(TMessage m)
{
Func<object, object> handler;
if (!_dictionary.TryGetValue(m.GetType(), out handler))
{
throw new Exception("cannot map " + m.GetType());
}
return (TResult) handler(m);
}
public void Dispatch<TMessage>(TMessage m)
{
Func<object, object> handler;
if (!_dictionary.TryGetValue(m.GetType(), out handler))
{
throw new Exception("cannot map " + m.GetType());
}
handler(m);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment