.net-coredomain-events

Granular domain events


Initially we were using Domain events to handle communications with external systems. For instance, every time a user was updating his phone number OR his name we raise a PhoneNumberUpdated AND a NameUpdated event. These are then caught by handlers processed and sent to other systems.

    public void SetName(Name name)
    {
        if (Name == name) return;
        (...)
        RaiseEvent(new NameUpdated(Id, name));
    }

    public void SetPhoneNumber(PhoneNumber number, PhoneNumberType type)
    {
        RaiseEvent(new PhoneNumberUpdated());
    }

It works great as long as we do not need to "aggregate" events. For example, we got a new requirement asking us to to send one single email whenever a user updates his name and/or his phone number. With the current structure, our handlers would be notified multiples times (one time for each event raised) and this would result in multiple emails sent.

Making our events more generic don't seem to be a good solution. But then how would we aggregate several events raised within one transaction?

Thx Seb


Solution

  • I believe your new requirement is a separate concern from your actual domain. Your domain generates events that describe what has happened. User notification, on the other hand, is a projection of that stream of events into email form. Just like you would keep your read model requirements separate from your domain, you should keep this separate as well.

    A simple solution would be to capture the events you care about into a table and then once a day, on a schedule, and send one email per aggregate.