Interface IEventHandler<TEvent>
Defines a handler for processing events in the messaging pipeline.
[SuppressMessage("Naming", "CA1711:Identifiers should not have incorrect suffix", Justification = "Event handler pattern intentionally uses the Handler suffix.")]
public interface IEventHandler<in TEvent> where TEvent : IDispatchEvent
Type Parameters
TEventThe type of event to handle.
- Extension Methods
Remarks
Implement this interface to react to events that have occurred in the system. Unlike action handlers, multiple event handlers can process the same event, supporting the publish-subscribe pattern. Common use cases include:
- Updating read models and projections
- Triggering workflows and side effects
- Sending notifications and alerts
- Maintaining audit logs and analytics
- Cache invalidation and synchronization
Event handlers should be idempotent as events may be redelivered. The contravariant in modifier allows handlers to process base event types.
Methods
HandleAsync(TEvent, CancellationToken)
Handles the specified event asynchronously.
Task HandleAsync(TEvent eventMessage, CancellationToken cancellationToken)
Parameters
eventMessageTEventThe event to handle.
cancellationTokenCancellationTokenThe cancellation token to observe.
Returns
- Task
A task representing the asynchronous operation.
Remarks
Implementations should be idempotent to handle potential redelivery. Event handlers execute independently; one handler's failure doesn't affect others. Consider the eventual consistency implications when designing event handlers.
A fault thrown here reaches the publisher unchanged when it is the only one: the publisher catches this exact exception type whether one handler or several are subscribed. Only when two or more handlers fail for the same event does the publisher see an AggregateException carrying all of them.