Last active
December 13, 2015 01:49
-
-
Save christopherbauer/7305a5222b516d7010cc to your computer and use it in GitHub Desktop.
EventBus pattern in C#
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 EventBus | |
{ | |
private Dictionary<Type, List<Action<IEvent>>> actions = new Dictionary<Type, List<Action<IEvent>>>(); | |
public void Listen<T>(Action<IEvent> callback) where T : IEvent | |
{ | |
if (!actions.ContainsKey(typeof(T))) | |
{ | |
actions.Add(typeof(T), new List<Action<IEvent>>()); | |
} | |
actions[typeof(T)].Add(callback); | |
} | |
public void ClearCallbacks<T>() where T : IEventMessage | |
{ | |
actions.Remove(typeof(T)); | |
} | |
public void Send<T>(T @event) where T : IEvent | |
{ | |
if (!actions.ContainsKey(typeof(T))) | |
{ | |
return; | |
} | |
foreach (var action in actions[typeof(T)]) | |
{ | |
action(@event); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment