Skip to content

3. Event Handling

Simon Heiss edited this page Feb 27, 2020 · 3 revisions

Microwave supports distributed systems and you can subscribe to events from any service with just implementing an interface. Microwave will get the events, put them in the handling classes and saves the location where you left of, in case a service is unavailable or an error occurs during the event handling on the client side.

Subscribing to Domain Events

If you want to react to DomainEvents in your Domain, to trigger other processes, you can do this by implementing the IHandleAsync interface in a class. You will have to implement a method that will receive the event as soon as it happens in the Domain. This all happens asynchronouse, so the emitting thread is not blocked by your handling. A handler could look like this:

public class WelcomeMailHandler : IHandleAsync<UserCreatedEvent>
{
    private readonly IMailRepository _mailRepository;

    public WelcomeMailHandler(IMailRepository mailRepository)
    {
        _mailRepository = mailRepository;
    }

    public Task HandleAsync(UserCreatedEvent domainEvent)
    {
        await _mailRepository.SendWelcomeMail(domainEvent.UserId);
    }
}

Using the IHandleAsync is usually useful when updating your write or read model when something happens in another entity that you do not want to reference directly.

Cron Timing of Updates

Microwave triggers an update for readmodels/querries every second by default. If you have readmodels that do not have to be updated frequently and if you want to save traffic, you can define the update cycle with the IPollingInterval in the startup class. The class accepts a string wich represents a cron notation or a integer which triggers the job every n full seconds. The T is the class that implements the IHandle or IHandleAsync interface. A registration could look like this:

public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMicrowave(config =>
    {
        config.PollingIntervals.Add(new PollingInterval<MyAsyncHandler>("* * * * 2")); // Update every two minutes
        config.PollingIntervals.Add(new PollingInterval<MyReadModel1>(20));            // Update every 20 seconds
    });
}

Clone this wiki locally