Tutorials ASP.NET Core Complete Tutorial (ShopNest)

CQRS Pattern with MediatR in ASP.NET Core

Learn CQRS Pattern with MediatR in ASP.NET Core in our free ASP.NET Core Complete Tutorial (ShopNest) series. Step-by-step explanations, examples, and interview tips on Toolliyo Academy.

On this page
CQRS Pattern with MediatR in ASP.NET Core — ShopNest
Article 45 of 75 · Module 6: Advanced Architecture · ShopNest Order Management System
Target keyword: cqrs mediatr asp.net core · Read time: ~34 min · .NET: 8 / 9 · Project: ShopNest Order Management System

Introduction

CQRS separates reads from writes — ShopNest Order Management uses MediatR so controllers send one command/query object and handlers contain the logic.

After this article you will

  • Implement commands and queries with IRequest
  • Build handlers and pipeline behaviors
  • Publish domain events as INotification
  • Combine CQRS with Clean Architecture layers
  • Understand read vs write model trade-offs

Prerequisites

Concept deep-dive

public record CreateOrderCommand(string CustomerId, List<OrderLineDto> Lines)
    : IRequest<Guid>;

public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, Guid>
{
    public async Task<Guid> Handle(CreateOrderCommand req, CancellationToken ct)
    {
        var order = Order.Create(req.CustomerId, req.Lines);
        await _repo.AddAsync(order, ct);
        await _publisher.Publish(new OrderCreatedEvent(order.Id), ct);
        return order.Id;
    }
}

public record GetOrderQuery(Guid OrderId) : IRequest<OrderDetailDto?>;

// Pipeline behavior — validation for all commands
public class ValidationBehavior<TReq, TRes> : IPipelineBehavior<TReq, TRes>
    where TReq : IRequest<TRes>
{
    public async Task<TRes> Handle(TReq req, RequestHandlerDelegate<TRes> next, CancellationToken ct)
    {
        await _validator.ValidateAndThrowAsync(req, ct);
        return await next();
    }
}

Same DB vs separate: Start with one database; split read models when read scale demands it. Event sourcing is optional advanced topic.

Hands-on — ShopNest Order Management System

  1. Install MediatR; register from Application assembly.
  2. CreateOrderCommand + GetOrderQuery handlers.
  3. LoggingBehavior and ValidationBehavior pipeline.
  4. OrdersController: await _mediator.Send(command).

Common errors & best practices

  • Fat handlers with 200 lines — extract domain services.
  • CQRS for every CRUD — overkill on simple modules.
  • Forgetting async all the way through handlers.

Interview questions

Q: CQRS benefit?
A: Independent scaling and models for reads vs writes; clearer intent per operation.

Q: MediatR purpose?
A: In-process mediator decoupling controllers from handlers + pipeline behaviors.

Q: IRequest vs INotification?
A: IRequest returns value (command/query); INotification is fire-and-forget event.

Summary

  • Commands mutate; queries read — separate handlers
  • MediatR pipeline cross-cuts validation and logging
  • Domain events decouple side effects (email, inventory)
  • Fits Clean Architecture Application layer perfectly

Previous: Clean Architecture
Next: Repository Pattern — Deep Dive

FAQ

MediatR performance?

Tiny in-process dispatch overhead — negligible vs DB I/O.

Event sourcing required?

No — CQRS does not imply event sourcing.

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

ASP.NET Core Complete Tutorial (ShopNest)
Course syllabus
Module 1: Foundations
Module 2: Entity Framework Core
Module 3: Dependency Injection & Middleware
Module 4: Authentication & Security
Module 5: Web API
Module 6: Advanced Architecture
Module 7: Testing
Module 8: Deployment & DevOps
Module 9: Real-World Projects
Module 10: Advanced Topics
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details