TaskHub.Shared

Outbox Pattern Integration

The Outbox pattern ensures that domain events are reliably published even if the message broker is temporarily unavailable.

How it Works

TaskHub.Shared integrates the Outbox pattern directly into the EF Core transaction flow via UnitOfWorkBase.

  1. Change Tracking: When SaveAsync is called on the Unit of Work, it scans the EF Core Change Tracker for any entities implementing IAggregate that are in a Added or Modified state.
  2. Event Extraction: It extracts all domain events from these aggregates.
  3. Conversion: Using the IOutboxMessageFactory, it converts each domain event into an OutboxMessage.
  4. Persistence: The OutboxMessage records are added to the same database transaction as your business data.
  5. Event Clearing: Once the events are safely added to the context, they are cleared from the aggregate roots to prevent double-processing.

Setup

1. Enable in Configuration

Ensure the Outbox is enabled in your appsettings.json.

"Persistence": {
  "Outbox": {
    "IsEnabled": true,
    "TableName": "OutboxMessages"
  }
}

2. Implement Aggregates

Ensure your domain entities inherit from AggregateBase<T>.

public class Order : AggregateBase<Guid>
{
    public void Complete()
    {
        // ... logic
        AddEvent(new OrderCompletedDomainEvent(Id));
    }
}

3. Unit of Work

Use UnitOfWorkBase as your base class. The SaveAsync method handles everything automatically.

await _unitOfWork.SaveAsync(ct); // Business data + Outbox messages saved in one transaction

Processing the Outbox

The TaskHub.Shared.Outbox.EntityFramework module provides the repository for reading and writing these messages. A separate background worker (or a recurring job) should use IOutboxReader to fetch pending messages and publish them to your message broker.