Skip to content

Instantly share code, notes, and snippets.

@codescribler
Last active August 29, 2015 14:08
Show Gist options
  • Save codescribler/e69b9a807a02ff058fb9 to your computer and use it in GitHub Desktop.
Save codescribler/e69b9a807a02ff058fb9 to your computer and use it in GitHub Desktop.
Example of a very simplistic internal message router
public class SimpleRouter
{
protected Dictionary<Type, List<Action<IEvent>>> Routes;
public SimpleRouter()
{
Routes = new Dictionary<Type, List<Action<IEvent>>>();
}
public void Register<T>(Action<T> handler) where T: IEvent
{
// I've included the DelegateAdjuster code in the download, but you could just you dynamic to simplify this
if(Routes.ContainsKey(typeof(T))) Routes[typeof(T)].Add(DelegateAdjuster.CastArgument<IEvent, T>(x => handler(x)));
Routes[typeof(T)] = new List<Action<IEvent>> { DelegateAdjuster.CastArgument<IEvent, T>(x => handler(x)) };
}
public void Handle(IEvent message)
{
Before(message);
foreach (Action<IEvent> action in Routes[message.GetType()])
{
action.Invoke(message);
}
After(message);
}
protected virtual void Before(IEvent message)
{
}
protected virtual void After(IEvent message)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment