Created
June 9, 2017 13:33
-
-
Save perokvist/2310c6f7a2bc2c16b86332903e369899 to your computer and use it in GitHub Desktop.
C# Command dispatcher
This file contains hidden or 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<TMessage, TResult> | |
| { | |
| private readonly IDictionary<Type, Func<TMessage, TResult>> _dictionary = new ConcurrentDictionary<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)) | |
| { | |
| return handler(m); | |
| } | |
| var aggregateMakers = m.GetType().GetTypeInfo().GetInterfaces(); | |
| if (aggregateMakers.Any(aggregateMaker => _dictionary.TryGetValue(aggregateMaker, out handler))) | |
| { | |
| return handler(m); | |
| } | |
| throw new Exception($"cannot dispatch {m.GetType()}); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment