Skip to content
João Simões edited this page Aug 21, 2017 · 3 revisions

To be able to notify application state change, this library has support for events that are broadcast into all event handlers using generic variance.

Components

The following interfaces and abstract classes are used to implement the event pattern:

Interface/Class Description
IEvent interface that represents an event
Event abstract class that implements the IEvent interface
IEventHandler<TEvent> interface that will handle asynchronously a TEvent instance extending from IEvent

Event properties

The following properties are included in the event interfaces:

Property Description
Id required unique identifier for each event. It may be used to detect event duplication or just for audit purposes. The abstract event class will assign a Guid.NewGuid() value
CreatedOn required date and time in which the event was created. The abstract event class will assign a DateTimeOffset.Now value
CreatedBy a string identifier for the user who created the event

Creating an event

To create an event just implement the IEvent interface or extend the Event class:

public class UserCreatedEvent : Event, IEvent {
  public User User { get; set; }
}

Handling an event

To handle an event just implement the IEventHandler<TEvent> interfaces:

public class CacheManager : IEventHandler<UserCreatedEvent> {
  public async Task HandleAsync(UserCreatedEvent evt, CancellationToken ct) {
    // add the new user to the cache
  }
}

Broadcast an event

To broadcast an event to all handlers, you only need the mediator instance and use the BroadcastAsync method:

await _mediator.BroadcastAsync<UserCreatedEvent>(new UserCreatedEvent {
  User = new User {
    Id = userId,
    Email = userEmail
  }
}, ct);
Clone this wiki locally