Skip to content

Subscribing for Events

Petar Marinov edited this page Jun 24, 2018 · 1 revision

There are two ways to subscribe for events:

  • by using the EventBroker.Subscribe overloads
  • by providing an IEventHandlerFactory implementation

both can be used side by side by single EventBroker instance.

Explicit subscribing

Subscription can be made by passing an implementaion of IEventHandler<TEvent>

public class MyEventHandler : IEventHandler<MyEvent>
{
    public void Handle(MyEvent @event) => Console.WriteLine(@event.Message);
    
    public bool ShouldHandle(MyEvent @event) => true;

    public void OnError(Exception error, MyEvent @event) => Console.WriteLine(error.Message);
}
...
var handler = new MyEventHandler();
eventBroker.Subscribe(handler);

If at some point we are not interested of the event any more we can use EventBroker.Unsubscribe to stop receiving events

eventBroker.Unsubscribe(handler);

the handler instance should be the same that was used when EventBroker.Subscribe was called.

There is an overload of EventBroker.Subscribe method taking delegates instead of IEventHandler<TEvent>

Subscribe<TEvent>(Action<TEvent> handler, Func<TEvent, bool> filter = null, Action<Exception, TEvent> onError = null);  

Equivalent of previous example is

eventBroker.Subscribe<MyEvent>(x => Console.WriteLine(x.Message), _=> true, (x, e) => Console.WriteLine(x.Message));

Note: the same instance of the delegate should be used for unsubscribing

There is also a DelegateEventHandler<TEvent> helper class that can be used to adapt delegate as IEventHandler<TEvent> implementation.

Subscribing via IEventHandlerFactory

If IEventHandlerFactory implementation is passed in EventBroker constructor, it will be called on every published event

IEnumerable<IEventHandler<TEvent>> HandlersFor<TEvent>();

Note: null is a valid return value

Implementations can use custom logic or be backed by IoC container for creating/resolving IEventHandler<TEvent> implementations.

Clone this wiki locally