Last active
August 29, 2015 14:08
-
-
Save codescribler/e69b9a807a02ff058fb9 to your computer and use it in GitHub Desktop.
Example of a very simplistic internal message router
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 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