Newsletter

Get the Thursday issue.

One focused C# tutorial. Free, and easy to leave.

  • 4,000+ engineers
  • 100+ tutorials
CQRS Pattern in ASP.NET Core

CQRS Pattern in ASP.NET Core

26 Nov 2026 · 7 min

Sponsor Newsletter

As applications grow in complexity, so does the logic behind how they handle data and operations.

A simple CRUD approach might work at first, but soon you’ll notice that read and write operations evolve in different directions.

Reads need fast, shaped data, while writes need rules and consistency. When both live in the same services, every change touches code it shouldn't.

That’s where the CQRS (Command Query Responsibility Segregation) pattern comes into play.

CQRS Pattern

CQRS stands for Command Query Responsibility Segregation. The main idea is simple:

  • Commands change the state of the application (e.g., creating or updating a record).
  • Queries read data without modifying anything.

By splitting these responsibilities, you gain better control over your application’s behavior and make it easier to scale each part independently.

However, it's best to start simple. CQRS is all about separation and it should first be implemented as a purely logical pattern, without separate databases or infrastructure.

This separation also makes your architecture more expressive. It’s immediately clear whether a part of code is responsible for reading or modifying data.

Later on, when scaling you can physically separate the read data from the write data.

In this blog post we'll start simple with purely logical CQRS. Physical isolation and syncing mechanisms may follow in future articles.

Commands

A Command represents an intention to perform an action, something that changes the state of your system.

To mark a model as a command, I use a simple ICommand interface. Its generic parameter is the type the command returns:

csharp
public interface ICommand<TResponse>;

Here's a command that creates a user and returns its id:

csharp
public record CreateUserCommand(
    string FirstName,
    string LastName,
    string Email) : ICommand<Guid>;

NOTE: Commands and queries are usually immutable models that carry only the data required to execute the action to their respective handlers.

Queries

A Query is used to fetch data, nothing more, nothing less. It must not modify the application state.

Queries get their own marker, IQuery:

csharp
public interface IQuery<TResponse>;

This query returns a UserDto, or null when the user doesn't exist:

csharp
public record GetUserByIdQuery(Guid UserId) : IQuery<UserDto?>;

public record UserDto(Guid Id, string FirstName, string LastName, string Email);

Handlers

Handlers contain the actual logic for executing commands and queries.

Each command has a corresponding Command Handler, and each query has a Query Handler. Both are described by an abstraction:

csharp
public interface ICommandHandler<in TCommand, TResponse>
    where TCommand : ICommand<TResponse>
{
    Task<TResponse> HandleAsync(TCommand command);
}

public interface IQueryHandler<in TQuery, TResponse>
    where TQuery : IQuery<TResponse>
{
    Task<TResponse> HandleAsync(TQuery query);
}

The generic constraint ties every handler to the response type its command or query declares.

Example Command Handler:

csharp
public class CreateUserCommandHandler
    : ICommandHandler<CreateUserCommand, Guid>
{
    private readonly AppDbContext _context;

    public CreateUserCommandHandler(AppDbContext context)
        => _context = context;

    public async Task<Guid> HandleAsync(CreateUserCommand command)
    {
        var user = new User(command.FirstName, command.LastName, command.Email);
        _context.Users.Add(user);
        await _context.SaveChangesAsync();
        return user.Id;
    }
}

Example Query Handler:

csharp
public class GetUserByIdQueryHandler
    : IQueryHandler<GetUserByIdQuery, UserDto?>
{
    private readonly AppDbContext _context;

    public GetUserByIdQueryHandler(AppDbContext context)
        => _context = context;

    public async Task<UserDto?> HandleAsync(GetUserByIdQuery query)
    {
        return await _context.Users
            .Where(u => u.Id == query.UserId)
            .Select(u => new UserDto(u.Id, u.FirstName, u.LastName, u.Email))
            .FirstOrDefaultAsync();
    }
}

By organizing logic this way, each handler has a single responsibility. It becomes easier to test, reason about and evolve independently.

DI Setup

Registering every handler in DI by hand doesn't look too bad at first. Then you realize that an application where CQRS makes sense has dozens, if not hundreds, of handlers.

Since every handler is marked with ICommandHandler or IQueryHandler, we can register all of them at once with Scrutor:

shell
dotnet add package Scrutor

The Scan method finds every class that implements one of the handler interfaces and registers it with a scoped lifetime:

csharp
public static class ServiceCollectionExtensions
{
    extension(IServiceCollection services)
    {
        internal IServiceCollection AddHandlers()
        {
            services.Scan(scan => scan
                .FromAssembliesOf(typeof(ServiceCollectionExtensions))
                .AddClasses(classes => classes.AssignableTo(typeof(ICommandHandler<,>)))
                    .AsImplementedInterfaces()
                    .WithScopedLifetime()
                .AddClasses(classes => classes.AssignableTo(typeof(IQueryHandler<,>)))
                    .AsImplementedInterfaces()
                    .WithScopedLifetime());

            services.Decorate(typeof(ICommandHandler<,>), typeof(LoggingCommandDecorator<,>));
            services.Decorate(typeof(IQueryHandler<,>), typeof(LoggingQueryDecorator<,>));

            return services;
        }
    }
}

New handlers are now picked up automatically. The Decorate calls at the end wrap every handler with logging, which we'll cover next.

Decorators

The same abstractions make it easy to add common concerns on top of every handler without touching them.

Here's a decorator that logs before and after each command:

csharp
internal sealed class LoggingCommandDecorator<TCommand, TResponse>(
    ICommandHandler<TCommand, TResponse> innerHandler,
    ILogger<LoggingCommandDecorator<TCommand, TResponse>> logger)
    : ICommandHandler<TCommand, TResponse>
    where TCommand : ICommand<TResponse>
{
    public async Task<TResponse> HandleAsync(TCommand command)
    {
        var commandName = typeof(TCommand).Name;

        logger.LogInformation("Handling {CommandName}", commandName);

        var response = await innerHandler.HandleAsync(command);

        logger.LogInformation("Handled {CommandName}", commandName);

        return response;
    }
}

LoggingQueryDecorator looks the same, it just wraps IQueryHandler instead.

If you want to learn more about automatic registration and decorators, check out my blog post about Scrutor: Scrutor in ASP.NET Core

Usage Example

With everything registered, endpoints simply inject the handler they need:

csharp
builder.Services
    .AddSwaggerGen()
    .AddEndpointsApiExplorer()
    .AddPersistence(builder.Configuration)
    .AddHandlers();

// ...

app.MapPost("users", async (
    CreateUserRequest request,
    ICommandHandler<CreateUserCommand, Guid> handler) =>
{
    var command = new CreateUserCommand(request.FirstName, request.LastName, request.Email);

    var userId = await handler.HandleAsync(command);

    return Results.Ok(userId);
});

app.MapGet("users/{id:guid}", async (
    Guid id,
    IQueryHandler<GetUserByIdQuery, UserDto?> handler) =>
{
    var user = await handler.HandleAsync(new GetUserByIdQuery(id));

    if (user is null)
    {
        return Results.NotFound();
    }

    return Results.Ok(user);
});

Since the container resolves the decorated handler, every request is logged without any extra code in the endpoints.

Conclusion

CQRS separates the code that changes state from the code that reads it.

You don't need separate databases to benefit from it. A purely logical split with commands, queries and dedicated handlers already makes your code easier to understand and test.

With a few simple abstractions, registering handlers and adding common concerns like logging stays effortless as the application grows.

If you want to check out examples I created, you can find the source code here:

Source Code

I hope you enjoyed it, subscribe and get a notification when a new blog is up!

Keep reading