Lesson 8 of 8
Mini Project: Event-Driven Order Processing
Build an event-driven order processing system: PlaceOrderCommand (MediatR) → Order aggregate (DDD) → OrderPlacedEvent → Domain event handlers dispatch 3 tasks asynchronously: (1) Send email via Hangfire, (2) Push SignalR update to tracking UI, (3) Deduct inventory via BackgroundService Channel.
Quick Quiz - Clean Architecture, DDD & Background Services
Event-Driven Order Architecture
// When PlaceOrderCommand is handled:
// 1. Order domain entity created → Place() method raises OrderPlacedEvent
// 2. DomainEventBehavior dispatches event after SaveChanges
// 3. Two MediatR notification handlers run in parallel:
// a. EmailNotificationHandler → schedules Hangfire job (email)
// b. SignalRNotificationHandler → pushes WebSocket update
public class EmailNotificationHandler
: INotificationHandler<OrderPlacedEvent2>
{
private readonly IBackgroundJobClient _hangfire;
public EmailNotificationHandler(IBackgroundJobClient hangfire) =>
_hangfire = hangfire;
public Task Handle(OrderPlacedEvent2 evt, CancellationToken ct)
{
// Schedule email in Hangfire - persisted, survives restart
_hangfire.Enqueue<IEmailService>(email =>
email.SendOrderConfirmationAsync(evt.OrderId, evt.CustomerId, default));
return Task.CompletedTask;
}
}
public class SignalRNotificationHandler(IHubContext<OrderTrackingHub2, IOrderClient> hub)
: INotificationHandler<OrderPlacedEvent2>
{
public async Task Handle(OrderPlacedEvent2 evt, CancellationToken ct) =>
await hub.Clients.User(evt.CustomerId.ToString())
.OrderPlaced(new OrderPlacedNotification(evt.OrderId, evt.Total, DateTime.UtcNow));
}
public class InventoryDeductionHandler(IBackgroundTaskQueue queue)
: INotificationHandler<OrderPlacedEvent2>
{
public async Task Handle(OrderPlacedEvent2 evt, CancellationToken ct) =>
await queue.EnqueueAsync(async token =>
{
// Runs in background thread - inventory service deducts stock
await Task.Delay(100, token); // simulate inventory update
Console.WriteLine($"Inventory deducted for order {evt.OrderId}");
}, ct);
}
// ━━ Architecture summary ━━
// HTTP POST /api/orders
// → MediatR.Send(PlaceOrderCommand)
// → LoggingBehavior: log start
// → ValidationBehavior: validate
// → PlaceOrderHandler: create Order aggregate, SaveChanges
// → DomainEventBehavior: dispatch OrderPlacedEvent
// → EmailNotificationHandler: Hangfire.Enqueue(SendEmail)
// → SignalRNotificationHandler: hub.Clients.User(...)
// → InventoryDeductionHandler: Channel.WriteAsync(DeductStock)
// → LoggingBehavior: log elapsed
// → HTTP 201 Created ← response in ~50ms
// Placeholder types
public record OrderPlacedEvent2(Guid OrderId, Guid CustomerId, string Total) : MediatR.INotification;
public interface INotificationHandler<T> { Task Handle(T n, CancellationToken ct); }
public interface IOrderClient { Task OrderPlaced(OrderPlacedNotification notification); }
public class OrderTrackingHub2 : Hub<IOrderClient> { }
public record OrderPlacedNotification(Guid OrderId, string Total, DateTime PlacedAt);
public interface IEmailService { Task SendOrderConfirmationAsync(Guid orderId, Guid customerId, CancellationToken ct); }
public interface IBackgroundJobClient { void Enqueue<T>(System.Linq.Expressions.Expression<Action<T>> job); }
public interface IBackgroundTaskQueue { Task EnqueueAsync(Func<CancellationToken, Task> work, CancellationToken ct = default); }
public interface Hub<T> { }
public interface IHubContext<THub, TClient> { IHubClients<TClient> Clients { get; } }
public interface IHubClients<T> { T User(string userId); }
public abstract class Hub<T> { }Tip
Tip
Practice Mini Project EventDriven Order Processing in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of Mini Project EventDriven Order Processing from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Mini Project EventDriven Order Processing is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?