Skip to content

Instantly share code, notes, and snippets.

@perokvist
Created June 9, 2017 13:33
Show Gist options
  • Select an option

  • Save perokvist/2310c6f7a2bc2c16b86332903e369899 to your computer and use it in GitHub Desktop.

Select an option

Save perokvist/2310c6f7a2bc2c16b86332903e369899 to your computer and use it in GitHub Desktop.
C# Command dispatcher
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