Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are domain events dispatched from within domain objects?

Domain objects shouldn't have any dependencies, hence no dependency injection either. However, when dispatching domain events from within domain objects, I'll likely want to use a centralised EventDispatcher. How could I get hold of one?

I do not want to return a list of events to the caller, as I'd like them to remain opaque and guarantee their dispatch. Those events should only be consumed by other domain objects and services that need to enforce an eventual consistent constraint.

like image 925
Double M Avatar asked Oct 25 '18 15:10

Double M


2 Answers

See Udi Dahan's domain events

Basically, you register one or more handlers for your domain events, then raise an event like this:

public class Customer
{
   public void DoSomething()
   {
      DomainEvents.Raise(new CustomerBecamePreferred() { Customer = this });
   }
}

And all the registered handler will be executed:

public void DoSomethingShouldMakeCustomerPreferred()
{
   var c = new Customer();
   Customer preferred = null;

   DomainEvents.Register<CustomerBecamePreferred>(p => preferred = p.Customer);

   c.DoSomething();
   Assert(preferred == c && c.IsPreferred);
}

This is basically implementing Hollywood Principle (Don't call us, we will call you), as you don't call the event handler directly - instead the event handler(s) get executed when the event is raised.

like image 153
Hooman Bahreini Avatar answered Oct 18 '22 18:10

Hooman Bahreini


I'll likely want to use a centralised EventDispatcher. How could I get hold of one?

Pass it in as an argument.

It probably won't look like an EventDispatcher, but instead like some Domain Service that describes the required capability in domain specific terms. When composing the application, you choose which implementation of the service to use.

like image 44
VoiceOfUnreason Avatar answered Oct 18 '22 19:10

VoiceOfUnreason