3

I'm wondering if domain event can be raised in domain service? I've got such a code written in C#. Of course it works, but is it correct from DDD point of view?

First example is related to user deletion. In my system Account has multiple users. After user removal AccountUserRemovedDomainEvent is raised. Then subscriber in infrastructure layer handles audit log management. It adds proper log describing this action.

public void RemoveUser(AccountUserEntity user, AccountEntity account)
{
  AccountUserRepository.Delete(user);
  DomainEvents.Raise(new AccountUserRemovedDomainEvent(user));
}

That's the second example. In that case except creating audit log subscriber in infrastructure layer is sending mail with activation link to the user.

public void SaveAccountUser(AccountUserBasicInformation information, AccountEntity account)
{
  var user = Mapper.Map<AccountUserEntity>(information);

  account.Users.Add(user);
  user.Account = account;

  DomainEvents.Raise(new AccountUserAddedDomainEvent(user));
}
  • 1
    The two examples that you show here do not match the "domain service" pattern described by Evans in the DDD book (see Chapter 5). – VoiceOfUnreason Jun 16 '20 at 03:48

1 Answers1

2

A domain event would typically be the result of an action/command being applied to a domain object. As such it probably wouldn't be something that a domain service is concerned with. You may need to have some technical system events/messages but those are a bit different and wouldn't be in domain services.

I like to have a method return the domain event(s) which facilitates testing, instead of a singleton that raises the events. If you end up with a domain service that interacts with multiple domain objects you may opt for returning the events but chances are, when using event sourcing anyway, that you'd need to the event streams that the events have to be added. Depending on your implementation the aggregate can keep track of new events also. In both scenarios you have a container for the event(s) so no need to return/raise them anyway.

Eben Roux
  • 12,983
  • 2
  • 27
  • 48