How Domain Events and Eventual Consistency work
mainThe system uses Domain Events to manage side effects without bloating single transactions. This allows for high performance and reactive behavior.
The Workflow:
- Atomic Update: A use case updates a single domain object within a single transaction (e.g., marking a subscription as
Canceled). - Event Dispatch: A
IDomainEventis added to the domain object during the update. - Queueing: Upon persisting changes, the
AppDbContextextracts these events and adds them to a queue in theHttpContext.Items. - Asynchronous Processing: After the HTTP response is sent, the
EventualConsistencyMiddlewaredequeues and publishes the events for offline processing (e.g., deleting related reminders).
// Example of adding an event within a domain method
public ErrorOr<Success> CancelSubscription(Guid subscriptionId)
{
// ... validation ...
Subscription = Subscription.Canceled;
_domainEvents.Add(new SubscriptionCanceledEvent(this, subscriptionId));
return Result.Success;
}