Domain Events

Domain Events are an integral part of Domain-Driven Design and are used to communicate changes and trigger side-effects within the domain model.

Domain Events represent real-world events or facts that are relevant to the business or domain. They capture important moments in the lifecycle of domain entities, aggregates, or value objects. By modeling and raising domain events, you can decouple different parts of your domain model and improve the overall maintainability and flexibility of your application.

Key characteristics of Domain Events:

  1. Immutable: Domain Events are usually immutable objects, meaning their state cannot be modified once created. This ensures that the event represents a specific occurrence at a particular moment.

  2. Side-effects: Domain Events are often used to trigger side-effects in response to certain actions or state changes. These side-effects can be in the form of notifications, logging, or updates to other parts of the domain model.

  3. Loose coupling: Raising Domain Events allows you to decouple different parts of the domain model. The entity or aggregate that raises the event doesn't need to know who will handle it, promoting a more flexible and extensible design.

  4. Event-driven architecture: Domain Events play a significant role in event-driven architectures, where different components or services communicate through events rather than direct method calls.

Eiffel.Modelling.Abstractions NuGet package contains base IDomainEvent interface. By using IDomainEvent interface you can define your domain events.

/// <summary>
/// Domain event interface
/// </summary>
public interface IDomainEvent
{
    /// <summary>
    /// Unique event identifier
    /// </summary>
    public Guid Id { get; }
}

By using Domain Events, you can ensure that various parts of your application remain loosely coupled, making it easier to understand, extend, and maintain the domain model. Example BookingCancelled domain event.

public class BookingCancelled : IDomainEvent
{
    public Guid Id { get; }

    public string BookingId { get; }

    public string CancellationReason { get; }

    public BookingCancelled(BookingId bookingId, string cancellationReason)
    {
        Id = Guid.NewGuid();
        BookingId = bookingId;
        CancellationReason = cancellationReason;
    }
}

Last updated