Created
November 27, 2013 20:17
-
-
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/
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 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