Skip to content

Domain events

Martin Havlišta edited this page Aug 27, 2018 · 44 revisions

Work in progress

When executing a domain behaviour on an aggregate root domain entity inside a database transaction, it is always a good idea to keep the transaction small and short. Some processing does not have to be necessarily part of the transaction, and can be done later (e.g. audit, sending email, subsequent domain processing, etc). CoreDdd supports domain events to defer some processing to a later time. The domain event is raised from a domain method on a domain entity, and announces that some domain activity has happened. Example:

    public class Policy : Entity, IAggregateRoot
    {
        ...
        public virtual void AddShipCargoPolicyItem(ShipCargoPolicyItemArgs args)
        {
            var shipCargoPolicyItem = new ShipCargoPolicyItem(args);
            _items.Add(shipCargoPolicyItem);

            DomainEvents.RaiseEvent(new ShipCargoPolicyItemAddedDomainEvent
            {
                PolicyId = Id,
                ShipId = args.Ship.Id
            });
        }
        ...
    }

CoreDdd supports two ways of domain even handling:

  • handling the domain events within the transaction
  • handling the domain events after the transaction

Clone this wiki locally