ASP.NET Core & Web API (50 Qs)•Part 3: Distributed Systems, Kestrel Internals & Scalability (25 - 35)
What is CQRS and how does MediatR implement the Mediator Pattern?
senior LevelCode ExampleSystem Design
In Simple Words:
- CQRS (Command Query Responsibility Segregation): Separates read operations (Queries) from write operations (Commands).
- MediatR: Decouples sender and handler:
IRequest<TResponse>dispatched viaISender.Send(command).- MediatR Pipeline Behaviors act as middleware around handlers for validation (FluentValidation), logging, and caching.
csharp
public record CreateUserCommand(string Email, string Name) : IRequest<Guid>;
public class CreateUserHandler : IRequestHandler<CreateUserCommand, Guid>
{
public async Task<Guid> Handle(CreateUserCommand request, CancellationToken ct)
{
// Business logic execution
return Guid.NewGuid();
}
}