Decoupling Use Cases with CQRS & Result Pattern
Part of Module 1: Enterprise Architecture & Solution Structuring
Replace bloated God Services with single-purpose MediatR commands/queries and eliminate expensive exception-based control flow using Result<T>.
What You Will Master in This Lesson
- Separate read queries from state-mutating write commands
- Implement a strongly-typed Result<T> pattern with categorized ErrorTypes
- Keep ASP.NET Core controllers thin using ProblemDetails mapping
1. Separating Reads from Writes (Pragmatic CQRS)
Traditional Repository + Service classes often grow into bloated 1,500-line "God Services" (OrderService.cs) containing dozens of unrelated methods. Pragmatic CQRS eliminates this by turning every action into a dedicated, single-purpose request and handler.
- Queries (Reads): Never mutate state. They bypass heavy change-tracking ORMs and project explicit columns directly from SQL Server into lightweight DTOs.
- Commands (Writes): Mutate state, validate business invariants, invoke Stored Procedures inside transaction boundaries, and return an explicit outcome.
2. Eliminating Exception-Driven Control Flow
Throwing exceptions like throw new DuplicateEmailException() for expected validation failures hurts throughput. Capturing a full CLR stack trace allocates memory and stalls execution threads under high load. Instead, model outcomes explicitly with a generic Result<T> wrapper:
namespace Platform.Application.Common;
public enum ErrorType { None, Validation, NotFound, Conflict, Unauthorized }
public sealed record Error(string Code, string Message, ErrorType Type = ErrorType.Validation)
{
public static readonly Error None = new(string.Empty, string.Empty, ErrorType.None);
}
public class Result<T>
{
public bool IsSuccess { get; }
public T? Value { get; }
public Error Error { get; }
private Result(bool isSuccess, T? value, Error error)
{
IsSuccess = isSuccess;
Value = value;
Error = error;
}
public static Result<T> Success(T value) => new(true, value, Error.None);
public static Result<T> Failure(Error error) => new(false, default, error);
}
3. Writing a Single-Purpose Command & Handler
Notice how readable, testable, and isolated the business flow becomes inside Platform.Application/Customers/CreateCustomer/:
public sealed record CreateCustomerCommand(string FullName, string Email)
: IRequest<Result<int>>;
public sealed class CreateCustomerHandler
: IRequestHandler<CreateCustomerCommand, Result<int>>
{
private readonly ICustomerRepository _customers;
public CreateCustomerHandler(ICustomerRepository customers)
{
_customers = customers;
}
public async Task<Result<int>> Handle(
CreateCustomerCommand command,
CancellationToken ct)
{
if (await _customers.ExistsByEmailAsync(command.Email, ct))
{
return Result<int>.Failure(
new Error("Customer.DuplicateEmail",
"A customer with this email already exists.",
ErrorType.Conflict));
}
var customer = Customer.Create(command.FullName, command.Email);
int newCustomerId = await _customers.InsertAsync(customer, ct);
return Result<int>.Success(newCustomerId);
}
}
4. Keeping Controllers Razor-Thin
Your Web API controller no longer contains try/catch blocks or business checks—it simply dispatches the command via MediatR and maps the Result<T> to standard HTTP status codes:
[ApiController]
[Route("api/v1/customers")]
public sealed class CustomersController : ControllerBase
{
private readonly ISender _sender;
public CustomersController(ISender sender) => _sender = sender;
[HttpPost]
[ProducesResponseType(typeof(int), StatusCodes.Status201Created)]
[ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status409Conflict)]
public async Task<IActionResult> Create(
[FromBody] CreateCustomerCommand command,
CancellationToken ct)
{
var result = await _sender.Send(command, ct);
if (result.IsSuccess)
return CreatedAtAction(nameof(GetById), new { id = result.Value }, result.Value);
return result.Error.Type switch
{
ErrorType.Conflict => Conflict(new ProblemDetails { Title = result.Error.Code, Detail = result.Error.Message }),
ErrorType.NotFound => NotFound(new ProblemDetails { Title = result.Error.Code, Detail = result.Error.Message }),
_ => BadRequest(new ProblemDetails { Title = result.Error.Code, Detail = result.Error.Message })
};
}
}
Hands-On Lab Exercise
Create a GetCustomerByIdQuery(int CustomerId) alongside a matching GetCustomerByIdHandler that returns Result<CustomerDto>. Return ErrorType.NotFound when the repository returns null, and verify Swagger shows clean 200 vs 404 status documentation.
Knowledge Check
Verify your understanding before advancing to the next lesson:
1. Why is Result<T> preferred over throwing custom exceptions for validation errors like duplicate emails?
2. In pragmatic CQRS, what is the key difference between a Query handler and a Command handler?