Search code examples
dependency-injectiondomain-driven-designdomain-events

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.


Solution

  • 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.