Skip to content

Instantly share code, notes, and snippets.

@christopherbauer
Last active December 13, 2015 01:49
Show Gist options
  • Save christopherbauer/7305a5222b516d7010cc to your computer and use it in GitHub Desktop.
Save christopherbauer/7305a5222b516d7010cc to your computer and use it in GitHub Desktop.
EventBus pattern in C#
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