Skip to main content

Lesson 8 of 8

Mini Project: E-Commerce Order Service

Build a complete order placement pipeline: PlaceOrderCommand → ValidationBehavior → Handler → Repository → Domain event → Email notification. Demonstrates Unit of Work, FluentValidation, CQRS, AutoMapper, Result<T>, and domain events - all wired together.

45 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Quick Quiz - Repository, Service Layer & DTOs

Complete Order Pipeline

Complete Order Pipeline
// ━━ PlaceOrderCommand → Validate → Deduct stock → Create order → Notify ━━

// Command
public record PlaceOrderCommand(Guid CustomerId, List<OrderLineItem> Items)
    : IRequest<Result<OrderResponse>>;

public record OrderLineItem(Guid ProductId, int Quantity);

// Validator
public class PlaceOrderValidator : AbstractValidator<PlaceOrderCommand>
{
    public PlaceOrderValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.Items).NotEmpty().WithMessage("Order must contain at least one item");
        RuleForEach(x => x.Items).ChildRules(item => {
            item.RuleFor(i => i.ProductId).NotEmpty();
            item.RuleFor(i => i.Quantity).GreaterThan(0).LessThanOrEqualTo(100);
        });
    }
}

// Handler
public class PlaceOrderHandler(
    IUnitOfWork uow,
    IPublisher publisher,
    ILogger<PlaceOrderHandler> logger) : IRequestHandler<PlaceOrderCommand, Result<OrderResponse>>
{
    public async Task<Result<OrderResponse>> Handle(
        PlaceOrderCommand command, CancellationToken ct)
    {
        // Load and validate products
        decimal total = 0;
        var orderItems = new List<OrderItem>();

        foreach (var line in command.Items)
        {
            var product = await uow.Products.FindByIdAsync(line.ProductId, ct);
            if (product is null) return Result<OrderResponse>.NotFound("Product", line.ProductId);
            if (product.Stock < line.Quantity)
                return Result<OrderResponse>.Validation([$"Insufficient stock for {product.Name}"]);

            product.Stock -= line.Quantity;
            uow.Products.Update(product);

            orderItems.Add(new OrderItem
            {
                Id = Guid.NewGuid(), ProductId = line.ProductId,
                Quantity = line.Quantity, UnitPrice = product.Price
            });
            total += product.Price * line.Quantity;
        }

        // Create order
        var order = new Order
        {
            Id = Guid.NewGuid(), CustomerId = command.CustomerId,
            Items = orderItems, Total = total, Status = "Placed",
            PlacedAt = DateTime.UtcNow
        };
        uow.Orders.Add(order);

        // Atomic save (stock + order in one transaction)
        await uow.SaveChangesAsync(ct);

        // Publish domain event (non-blocking - after commit)
        await publisher.Publish(new OrderPlacedEvent(order.Id, command.CustomerId, total), ct);

        logger.LogInformation("Order {OrderId} placed for customer {CustomerId}", order.Id, command.CustomerId);

        return Result<OrderResponse>.Success(new OrderResponse(order.Id, order.Status, order.Total, order.PlacedAt));
    }
}

// Domain event + handler
public record OrderPlacedEvent(Guid OrderId, Guid CustomerId, decimal Total) : INotification;
public class SendOrderConfirmationEmail : INotificationHandler<OrderPlacedEvent>
{
    public async Task Handle(OrderPlacedEvent evt, CancellationToken ct)
    {
        // enqueue email to background worker
        await Task.CompletedTask;
    }
}

// Types
class Product { public Guid Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } public int Stock { get; set; } }
class Order { public Guid Id { get; set; } public Guid CustomerId { get; set; } public List<OrderItem> Items { get; set; } = []; public decimal Total { get; set; } public string Status { get; set; } = ""; public DateTime PlacedAt { get; set; } }
class OrderItem { public Guid Id { get; set; } public Guid ProductId { get; set; } public int Quantity { get; set; } public decimal UnitPrice { get; set; } public Guid OrderId { get; set; } }
record OrderResponse(Guid Id, string Status, decimal Total, DateTime PlacedAt);
record Result<T>(bool IsSuccess, T? Value = default, string? Error = null)
{
    public static Result<T> Success(T v) => new(true, v);
    public static Result<T> NotFound(string r, object id) => new(false, Error: $"{r} {id} not found");
    public static Result<T> Validation(string[] e) => new(false, Error: string.Join("; ", e));
}
interface IUnitOfWork { IProductRepository Products { get; } IOrderRepository Orders { get; } Task<int> SaveChangesAsync(CancellationToken ct); }
interface IProductRepository { Task<Product?> FindByIdAsync(Guid id, CancellationToken ct); void Update(Product p); }
interface IOrderRepository { void Add(Order o); }
interface IPublisher { Task Publish<T>(T n, CancellationToken ct); }
interface INotification { }
interface INotificationHandler<T> { Task Handle(T n, CancellationToken ct); }
abstract class AbstractValidator<T> { protected void RuleFor<TProp>(Func<T, TProp> f) { } protected void RuleForEach<TProp>(Func<T, System.Collections.Generic.IEnumerable<TProp>> f) { } }

Tip

Tip

Practice Mini Project ECommerce Order Service in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project ECommerce Order Service 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 ECommerce Order Service is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done