Domain Driven Design: Handling Domain events and Integration events in Deep system.

Amr elshaer
4 min readApr 20, 2024

--

This story will begin with the basic scenario of publishing and handling events in dotnet application using mediator, command CreateOrderCommand, and in the create order aggregate add OrderCreatedDomainEvent and OrderCreatedIntegrationEvent, in save change in DB context will publish domain events and will use Outbox pattern to guarantee Atomicity of integration event with the same transaction, you can learn about outbox pattern from here

Base entity class the contain collection of domain events and integration events

we will begin with a happy scenario in creating an order that will add the domain event that the order was created and the integration event that will send mail that the order was created.

Order

OrderPlaced domain event

OrderPlaced domain evet

OrderPlaced handler of the domain event

OrderPlaced integration event

OrderPlaced integration event handler

Dbcontext override on save changes publish domain events and add integration events in the outbox

We add a process outbox message that will get messages from the outbox and publish them, I use Quartz to generate job

The handle of ProcessOutboxCommand gets the message and publishes and mark is processed

All this is great if the level of the add domain event and integration event is in one level not depth of aggregate, the problem here is if the domain handle of event add another domain event and integration event in this case this event not handled. like this

In the handle of order placed, we create a payment, payment create add two events payment created domain event, and add integration event also send notification that payment created success.

If we enter the implementation of create payment we will see

we notice that we added a domain event that payment created a domain event and another for the integration event, to handle publishing this events , we can make a decorator class (using decorator pattern)to get all events after calling the handle method of the event and publish them like this,

this decorator any event published will first enter this decorator so it handles and then dispatch events. second we need to configure this in configuration file,

you may ask why not use PipelineBehavior like Authorization and Validation behavior that is built in Mediator unfortunately mediator does not build a Behavior pipeline in INotification it is built for command only.

you can find all source code here

--

--