Why Do We Use Domain Events?

Listen to this Post

A domain event is something that happened in the domain, and other parts of the system should be aware of it. You can use domain events to build a loosely coupled system.

You Should Know:

To implement Domain Events effectively, you can use Entity Framework Core (EF Core) and MediatR, but here’s how you can do it without MediatR for better control:

1. Defining a Domain Event

public interface IDomainEvent { }

public class OrderPlacedEvent : IDomainEvent 
{ 
public int OrderId { get; } 
public DateTime OccurredOn { get; }

public OrderPlacedEvent(int orderId) 
{ 
OrderId = orderId; 
OccurredOn = DateTime.UtcNow; 
} 
} 

2. Dispatching Domain Events

public static class DomainEventDispatcher 
{ 
public static void Raise<T>(T domainEvent) where T : IDomainEvent 
{ 
// Publish to in-memory handlers 
foreach (var handler in GetHandlers<T>()) 
{ 
handler.Handle(domainEvent); 
} 
}

private static IEnumerable<IDomainEventHandler<T>> GetHandlers<T>() where T : IDomainEvent 
{ 
// Use DI or manual registration 
return ServiceLocator.ResolveAll<IDomainEventHandler<T>>(); 
} 
} 

3. Handling Domain Events

public interface IDomainEventHandler<in T> where T : IDomainEvent 
{ 
void Handle(T domainEvent); 
}

public class OrderPlacedHandler : IDomainEventHandler<OrderPlacedEvent> 
{ 
public void Handle(OrderPlacedEvent domainEvent) 
{ 
Console.WriteLine($"Order {domainEvent.OrderId} was placed at {domainEvent.OccurredOn}"); 
} 
} 
  1. Using EF Core to Track Domain Events
    public abstract class Entity 
    { 
    private List<IDomainEvent> _domainEvents = new(); </li>
    </ol>
    
    public IReadOnlyCollection<IDomainEvent> DomainEvents => _domainEvents.AsReadOnly();
    
    public void AddDomainEvent(IDomainEvent eventItem) => _domainEvents.Add(eventItem); 
    public void ClearDomainEvents() => _domainEvents.Clear(); 
    }
    
    // Inside your DbContext SaveChanges: 
    public override int SaveChanges() 
    { 
    var entitiesWithEvents = ChangeTracker.Entries<Entity>() 
    .Select(e => e.Entity) 
    .Where(e => e.DomainEvents.Any()) 
    .ToArray();
    
    var result = base.SaveChanges();
    
    foreach (var entity in entitiesWithEvents) 
    { 
    foreach (var domainEvent in entity.DomainEvents) 
    { 
    DomainEventDispatcher.Raise(domainEvent); 
    } 
    entity.ClearDomainEvents(); 
    }
    
    return result; 
    } 
    

    5. Linux/Windows Commands for Debugging

    • Check .NET Processes (Linux):
      ps aux | grep dotnet 
      
    • Windows Event Logs (PowerShell):
      Get-EventLog -LogName Application -Source ".NET Runtime" 
      
    • Logging in .NET Core (Linux):
      journalctl -u your-dotnet-service --no-pager -n 100 
      

    What Undercode Say

    Domain Events help decouple business logic, making systems more maintainable. Avoid overusing MediatR if manual control is needed. Use EF Core for tracking and custom dispatchers for flexibility.

    Expected Output:

    A decoupled system where domain events trigger side effects without tight dependencies.

    Relevant URLs:

    References:

    Reported By: Milan Jovanovic – Hackers Feeds
    Extra Hub: Undercode MoN
    Basic Verification: Pass ✅

    Join Our Cyber World:

    💬 Whatsapp | 💬 TelegramFeatured Image