This design pattern works on the concept of subscriber-publisher interaction, similar to the message brokers. 📫
System does not provide protection from duplicate events invocation.
IEventListener
- listener/handler of the event. (subscriber) 👂
IEvent
- event object that can be handled by listeners. ⬛
IEventBus
- bus where any publisher can raise new event, can be used as a listener to replicate passed events. ⚙️
- Declaration of the event. (
IEvent
is a marker interface which allows us to treat object as an event)
public class SomeEvent : IEvent
{
public int SomeParameter;
}
- Bus instantiation.
IEventBus bus = new EventBus();
- Listener instantiation and usage.
// consider that this code is from the other system component
void LogHandler(SomeEvent @event) =>
Console.WriteLine("SomeParameter: {0}", @event.SomeParameter);
var handler = LogHandler; // delegate
var listener = handler.ToListener(); // = new EventListener<SomeEvent>(handler);
var listenerEntry = listener.Listen(bus);
- Raising events.
SomeEvent @event = new () { SomeParameter = 42 };
await @event.Raise(bus);
- Listener dispose.
listenerEntry.Dispose(); // listener entry will not handle any more events from the bus it listens to