Skip to content

CQRS Pattern ​

Gryd.Application provides MediatR marker and handler interfaces for commands and queries. A command can use any response type; the common Gryd convention is Result or Result<T>. Queries return their response directly and should not change application state.

Commands ​

InterfaceDescription
ICommand<TResponse>Command with a response
ICommandCommand returning Result
ICommandHandler<TCommand, TResponse>Handler for a typed response
ICommandHandler<TCommand>Handler for Result commands

This example defines application-owned repository and entity types to show the handler dependencies. They are not Gryd.IO repository APIs.

csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using Gryd.Application.Abstractions.Messaging;
using Gryd.Domain.Models;

public sealed record User(Guid Id, string Email, string Name);

public interface IUserRepository
{
    Task AddAsync(User user, CancellationToken cancellationToken);
}

public sealed record CreateUserCommand(string Email, string Name)
    : ICommand<Result<Guid>>;

public sealed class CreateUserCommandHandler(IUserRepository repository)
    : ICommandHandler<CreateUserCommand, Result<Guid>>
{
    public async Task<Result<Guid>> Handle(CreateUserCommand request, CancellationToken ct)
    {
        var user = new User(Guid.NewGuid(), request.Email, request.Name);
        await repository.AddAsync(user, ct);
        return Result<Guid>.Success(user.Id);
    }
}

Register the assembly that contains handlers with AddGrydCore; see Core API extensions.

Queries ​

InterfaceDescription
IQuery<TResponse>Query with a response
IQueryHandler<TQuery, TResponse>Handler for a query response

The query repository and DTO below are also application-owned types.

csharp
using System;
using System.Threading;
using System.Threading.Tasks;
using Gryd.Application.Abstractions.Messaging;

public sealed record UserDto(Guid Id, string Email);

public interface IUserReadRepository
{
    Task<UserDto?> GetByIdAsync(Guid id, CancellationToken cancellationToken);
}

public sealed record GetUserByIdQuery(Guid Id) : IQuery<UserDto?>;

public sealed class GetUserByIdQueryHandler(IUserReadRepository repository)
    : IQueryHandler<GetUserByIdQuery, UserDto?>
{
    public Task<UserDto?> Handle(GetUserByIdQuery request, CancellationToken ct)
        => repository.GetByIdAsync(request.Id, ct);
}

Queries use MediatR's IRequest<TResponse> contract and return the response directly.

Released under the MIT License.