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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With