CQRS
Command and Query Responsibility Segregation (CQRS): a architectural style that separates read and write operations for a data store. Implementing CQRS in your application can maximize its performance, scalability, and security
- Commands: operations that change state (create, update, delete)
- Queries: operations that return data without changing state (read)
CQRS is based on the principle of Command Query Separation (CQS), which states that a method should either be a command that performs an action or a query that returns data, but not both. By separating commands and queries, CQRS allows for more flexible and scalable architectures
CQRS can be implemented in various ways, from having single database with separate read and write services which have synchronized views of the data, to using different databases for read and write operations which are eventually consistent (data may not be immediately consistent across read and write models)
The flexibility created by migrating to CQRS allows a system to better evolve over time and prevents update commands from causing merge conflicts at the domain level
MediatRpackage- Create a folder called
Queries - There add a class that gets item: Use
records
public static class GetTodoById {
// Query / Command
// All the data we need to execute
public record Query(int Id): IRequest < Response > ;
// Handler
// All the business logic to execute. Returns a response
public class Handler: IRequestHandler < Query, Response > {
private readonly Repository _repository;
public Handler(Repository, repository) {
_repository = repository;
}
public async Task < Response > Handle(Query request, CancellationToken cancellationToken) {
// All the business logic
var todo = _repository.Todos.FirstOrDefault(x => x.Id == request.Id);
}
}
// Response
// The data we want to return
public record Response(int Id, string Name, bool Completed);
}References:
- CQRS, Task Based UIs, Event Sourcing agh!
- Greg Young's Blog: CQRS
CQRS is not a silver bullet
CQRS is not a top level architecture
CQRS is not new
CQRS is not shiny
CQRS will not make your jump shot any better
CQRS is not intrinsically linked to DDD
CQRS is not Event Sourcing
CQRS does not require a message bus
CQRS is not a guiding principle / CQS is
CQRS is not a good wife
CQRS is learnable in 5 minutes
CQRS is a small tactical pattern
CQRS can open many doors
And yes you can support RFC 2549 using CQRS
Checkout this YouTube channel
Mediator
The Mediator design pattern defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently
