Skip to content

Part 3 of 12 in Clean Architecture in .NET

Setting Up the Application Layer in Clean Architecture: CQRS Without MediatR

· 14 min read

The application layer turns requests into use cases. This article builds one in .NET without MediatR, with small command and query handlers, validation and logging decorators, and tests for the validators. It is Part 3 of the Clean Architecture in .NET series.

In Part 2, the domain got its entities, value objects, Result and events. This part builds the layer around it: Ecommerce.Application, where each use case is a command or a query with one handler. The examples come from EcommerceApp’s products and orders.

This part adds EF Core, FluentValidation and Scrutor to Application. Here is Ecommerce.Application.csproj after this part:

<ItemGroup>
  <PackageReference Include="FluentValidation.DependencyInjectionExtensions" />
  <PackageReference Include="Microsoft.EntityFrameworkCore" />
  <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" />
  <PackageReference Include="Scrutor" />
</ItemGroup>

<ItemGroup>
  <ProjectReference Include="..\Ecommerce.Domain\Ecommerce.Domain.csproj" />
</ItemGroup>

The versions go in Directory.Packages.props (Part 1), and this part’s file has them. The only project reference is still Domain. The article explains the main types, and this part’s code has the rest, such as the logging decorator and PagedList<T>.

Commands and queries without MediatR

CQRS means a request either changes something (a command) or reads something (a query), and the two are written as separate types. Many .NET projects get this from MediatR. I don’t use it here. CQRS, and what we are implementing, don’t need MediatR. MediatR made the setup easier, which is why developers used it. But setting up what we actually need isn’t that difficult, and we can implement it like this.

What we need is four small interfaces in Abstractions/Messaging:

public interface ICommand;

public interface ICommand<TResponse>;

public interface IQuery<TResponse>;

public interface ICommandHandler<in TCommand>
    where TCommand : ICommand
{
    Task<Result> HandleAsync(TCommand command, CancellationToken cancellationToken);
}

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

public interface IQueryHandler<in TQuery, TResponse>
    where TQuery : IQuery<TResponse>
{
    Task<Result<TResponse>> HandleAsync(TQuery query, CancellationToken cancellationToken);
}
  • ICommand and IQuery<TResponse> are markers. They carry no members. They only say what kind of request a record is.
  • A command with no value to return uses ICommandHandler<TCommand> and returns Result. A command with a value, such as the ID of an edited product, uses the two-parameter form and returns Result<TResponse>.
  • Every handler returns a Result (Part 2), so a business rejection is a return value and not an exception.

A request is a record next to its handler:

public record EditProductCommand(Guid Id, string Name, string Description, string PriceCurrency, decimal PriceAmount, int Quantity, Guid CategoryId) : ICommand<Guid>;

One folder per use case holds the command, its handler and its validator. For example, Products/EditProduct/ has EditProductCommand, EditProductCommandHandler and EditProductCommandValidator.

The cost: there is no mediator, so the caller needs the handler itself. The controller takes the handler it needs as a parameter. That is one more constructor or action parameter, and I prefer it to hiding the call behind Send.

Registering the handlers with Scrutor

Registering each handler by hand is easy to forget. Scrutor scans the assembly and registers every class that implements a handler interface:

private static readonly Type[] HandlerInterfaces =
[
    typeof(ICommandHandler<>),
    typeof(ICommandHandler<,>),
    typeof(IQueryHandler<,>),
    typeof(IDomainEventHandler<>),
];

public static IServiceCollection AddApplication(this IServiceCollection services)
{
    services.Scan(scan => scan
        .FromAssemblies(typeof(DependencyInjection).Assembly)
        .AddClasses(classes => classes.AssignableToAny(HandlerInterfaces), publicOnly: false)
        .AsImplementedInterfaces()
        .WithScopedLifetime());

    // ...the decorators, below
}
  • The handler interfaces are listed once, and one scan registers every class that implements any of them.
  • publicOnly: false is there because the handlers are internal sealed. Only Application needs to see a handler class. Everyone else uses the interface.
  • Scoped, because a handler uses the DbContext, which lives for one request.
  • IDomainEventHandler<> is for the domain event handlers. They are covered at the end of this part.

A new use case needs no registration. Add the files and the handler is found.

Validation and logging as decorators

Every command needs two things besides the use case itself: its input checked, and a log line when it starts and ends. Without a shared place, each handler repeats both, and one of them forgets.

A decorator is a handler that wraps another handler of the same interface. It does its work, then calls the inner one. Scrutor’s TryDecorate replaces the registered handler with a decorator that wraps it.

This is the validating wrapper for a command that returns a value, in ValidatingHandlers.cs. The file also has one for commands without a response and one for queries, and a small helper the three share:

internal sealed class ValidatingCommandHandler<TCommand, TResponse>(
    ICommandHandler<TCommand, TResponse> inner,
    IEnumerable<IValidator<TCommand>> validators)
    : ICommandHandler<TCommand, TResponse>
    where TCommand : ICommand<TResponse>
{
    public async Task<Result<TResponse>> HandleAsync(TCommand command, CancellationToken cancellationToken)
    {
        ValidationError? error = await RequestValidation.ValidateAsync(command, validators, cancellationToken);

        return error is null
            ? await inner.HandleAsync(command, cancellationToken)
            : Result.Failure<TResponse>(error);
    }
}

internal static class RequestValidation
{
    // The validators run one after another, not in parallel: an async rule may use the request's
    // scoped DbContext, which can't run two operations at the same time.
    public static async Task<ValidationError?> ValidateAsync<TRequest>(
        TRequest request,
        IEnumerable<IValidator<TRequest>> validators,
        CancellationToken cancellationToken)
    {
        List<Error> errors = [];

        foreach (IValidator<TRequest> validator in validators)
        {
            FluentValidation.Results.ValidationResult result = await validator.ValidateAsync(request, cancellationToken);

            // The field name is the error's name, so the client sees which field is wrong.
            errors.AddRange(result.Errors.Select(failure => Error.BadRequest(failure.PropertyName, failure.ErrorMessage)));
        }

        return errors.Count == 0 ? null : new ValidationError(errors);
    }
}

It runs every FluentValidation validator registered for the command. If there are failures, it returns a Result with a ValidationError and the handler never runs. Each failure becomes an Error named after the field, so the client sees which field is wrong.

Why one after another? Running the validators with Task.WhenAll looks faster, but an async rule that checks the database uses the request’s DbContext, and a DbContext can’t run two queries at once. The request’s cancellation token is passed on too, so a cancelled request stops validating.

ValidationError lives in the domain next to Error. It is an Error that carries a list of errors:

public sealed record ValidationError(IReadOnlyList<Error> Errors)
    : Error("Validation.General", "One or more validation errors occurred", HttpStatusCode.BadRequest)
{
    public static ValidationError Collect(params IEnumerable<Result> results) =>
        new([.. results.Where(result => result.IsFailure).Select(result => result.Error)]);
}

The handler below uses Collect to gather the failures of several value objects at once. The validators are ordinary classes, one per command, and AddValidatorsFromAssembly registers them. Here is one, shortened:

public class RegisterUserCommandValidator : AbstractValidator<RegisterUserCommand>
{
    public RegisterUserCommandValidator()
    {
        RuleFor(c => c.FirstName).NotEmpty().MaximumLength(FirstName.MaxLength);
        RuleFor(c => c.LastName).NotEmpty().MaximumLength(LastName.MaxLength);
        RuleFor(c => c.Email).NotEmpty().EmailAddress().MaximumLength(Email.MaxLength);
        RuleFor(c => c.Password).NotEmpty().MinimumLength(8);
    }
}

It gives early feedback on each field. The value objects still guard themselves (Part 2).

The logging wrappers in LoggingHandlers.cs have the same shape. They log Processing command {Command}, call the inner handler, then log Completed command {Command}. When the handler fails, they log Completed command {Command} with error {ErrorCode}: {ErrorDescription} as an error instead, with the error’s code and description as template properties. The messages are declared once with [LoggerMessage], so the source generator writes the logging code at compile time:

internal static partial class HandlerLog
{
    [LoggerMessage(Level = LogLevel.Information, Message = "Processing command {Command}")]
    public static partial void CommandStarted(ILogger logger, string command);

    [LoggerMessage(Level = LogLevel.Error, Message = "Completed command {Command} with error {ErrorCode}: {ErrorDescription}")]
    private static partial void CommandFailed(ILogger logger, string command, string errorCode, string errorDescription);

    // ...the success and query messages have the same shape.
}

Why the generator here? Because these wrappers run on every request. A call like logger.LogInformation("...", name) parses its template and puts its arguments in an array on every call, even when the level is turned off. The generated method parses the template once at compile time and checks the level first. Elsewhere, plain ILogger calls are fine, which is why CA1848 stays off in .editorconfig. Application still needs only Microsoft.Extensions.Logging.Abstractions, not a logging library.

The order is set in DependencyInjection.cs:

services.TryDecorate(typeof(ICommandHandler<>), typeof(ValidatingCommandHandler<>));
services.TryDecorate(typeof(ICommandHandler<,>), typeof(ValidatingCommandHandler<,>));
services.TryDecorate(typeof(IQueryHandler<,>), typeof(ValidatingQueryHandler<,>));

services.TryDecorate(typeof(ICommandHandler<>), typeof(LoggingCommandHandler<>));
services.TryDecorate(typeof(ICommandHandler<,>), typeof(LoggingCommandHandler<,>));
services.TryDecorate(typeof(IQueryHandler<,>), typeof(LoggingQueryHandler<,>));

services.AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly);

Each call wraps what is registered so far. So logging is registered last and is the outermost. A command flows like this:

  • the logging decorator logs “Processing”
  • the validation decorator runs the validators
  • the handler runs, only if validation passed
  • the logging decorator logs “Completed”, or the error

Why is logging outside validation? Because then a command rejected by validation is also logged, with its errors. Each decorator exists three times, once per handler interface (commands with and without a response, and queries), because they are different generic types, so one class can’t cover them all.

Queries go through the same validation. A query without a validator passes straight through, because with no validators registered, ValidateAsync finds no errors. So a search query can reject an unknown sort column or an oversized page with a 400, and its handler never validates anything itself.

Why decorators and not MediatR’s pipeline behaviors? Pipeline behaviors are a ready-made way to wrap every handler with logging and validation, and they work. But wrapping a handler is the decorator pattern, and the pattern is small: one class per concern, registered with Scrutor’s TryDecorate. That isn’t complicated enough to need a library. So the handlers depend on my own ICommandHandler and IQueryHandler, and nothing in Application needs MediatR.

The DbContext in handlers, a repository for SQL

The handlers need the database, but Application can’t reference Infrastructure. So Application declares what it needs:

public interface IApplicationDbContext
{
    DbSet<Category> Categories { get; }
    DbSet<Coupon> Coupons { get; }
    DbSet<Product> Products { get; }
    DbSet<Order> Orders { get; }
    DbSet<Review> Reviews { get; }
    DbSet<User> Users { get; }

    Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
}

Infrastructure implements the interface.

I use the DbContext directly in the handlers instead of a repository per aggregate. The repository pattern has real benefits: an abstraction over data access, testability, query logic in one place, and a consistent way for the team to reach data. I agree with those. I also agree that EF Core’s DbContext already acts like a repository, so putting another abstraction on top of it feels unnecessary.

But the repositories don’t stay small. Command handlers need new operations and new filters on entity properties all the time. Each one becomes a new repository method, so the repositories and their methods keep growing, and that becomes a headache to maintain. So most CRUD goes through the DbContext.

That doesn’t mean no repository at all. I still put a repository in front of:

  • read queries that join multiple tables and return selected columns
  • existing stored procedures
  • complex operations that are easier or more efficient in raw SQL

Those use Dapper behind an interface that Application declares, with the implementation in Infrastructure.

The cost of IApplicationDbContext shows in the .csproj at the start of this part. DbSet<T> is an EF Core type, so Application references Microsoft.EntityFrameworkCore. The interface isn’t a pure abstraction. A handler can write any query EF Core allows, and a different ORM would mean changing the handlers. The four-project rule from Part 1 still holds: Application references only Domain, and the architecture tests confirm it. What I give up is a data layer with no knowledge of EF Core. I judged that less costly than a growing set of repositories.

One handler end to end

Every command handler has the same shape: load, call the domain, save, return a Result. This is EditProductCommandHandler:

internal sealed class EditProductCommandHandler(
    IApplicationDbContext dbContext,
    TimeProvider timeProvider)
    : ICommandHandler<EditProductCommand, Guid>
{
    public async Task<Result<Guid>> HandleAsync(EditProductCommand request, CancellationToken cancellationToken)
    {
        Product? product = await dbContext.Products.FirstOrDefaultAsync(product => product.Id == new ProductId(request.Id), cancellationToken);

        if (product is null)
        {
            return Result.Failure<Guid>(ProductErrors.NotFound);
        }

        Result<ProductName> name = ProductName.Create(request.Name);
        Result<ProductDescription> description = ProductDescription.Create(request.Description);
        Result<Currency> currency = Currency.FromCode(request.PriceCurrency);

        if (name.IsFailure || description.IsFailure || currency.IsFailure)
        {
            return Result.Failure<Guid>(ValidationError.Collect(name, description, currency));
        }

        Result updateResult = Product.Update(
            product,
            name.Value,
            description.Value,
            new Money(request.PriceAmount, currency.Value),
            request.Quantity,
            new CategoryId(request.CategoryId),
            timeProvider.GetUtcNow().UtcDateTime);

        if (updateResult.IsFailure)
        {
            return Result.Failure<Guid>(updateResult.Error);
        }

        await dbContext.SaveChangesAsync(cancellationToken);

        return product.Id.Value;
    }
}

Step by step:

  • Load the product with the DbContext. A missing one is ProductErrors.NotFound.
  • Turn the raw input into value objects. Each Create returns a Result, and all failures go back together as one ValidationError.
  • Call the domain with the time from TimeProvider. The handler doesn’t decide anything about the product. Product.Update does.
  • On a failure, return before saving. Nothing is written.
  • Save and return the ID.

The handler contains no business rule. If a rule shows up here, it belongs in the domain.

The ports

The rest of what Application needs from outside is a small interface each, in Abstractions, such as the email sender:

public interface IEmailService
{
    Task SendAsync(Email email, string subject, string body);
}

These are called ports because Application owns the shape and Infrastructure plugs in the implementation. IEmailService takes the domain’s Email value object, which is why Application can use it without any email library.

The clock is the one thing that needs no port of its own. Handlers take .NET’s TimeProvider (built in since .NET 8) and call timeProvider.GetUtcNow().UtcDateTime. That’s why a handler never calls DateTime.UtcNow: Infrastructure registers TimeProvider.System, and a test can hand the handler a fixed time instead, for example with FakeTimeProvider from Microsoft.Extensions.TimeProvider.Testing. A custom IDateTimeProvider interface would do the same job with one more type to maintain.

Paging has one type, PagedList<T>, with the items, the page, the page size, the total count, and HasPreviousPage and HasNextPage. A search query returns Result<PagedList<ProductResponse>>. It lives in Application because the handlers build it.

Domain event handlers

Part 2 ended with Order raising OrderPlacedDomainEvent and not knowing about email. This is the other side, a handler in Application:

internal sealed class SendOrderConfirmationDomainEventHandler(
    IApplicationDbContext dbContext,
    IEmailService emailService)
    : IDomainEventHandler<OrderPlacedDomainEvent>
{
    public async Task HandleAsync(OrderPlacedDomainEvent domainEvent, CancellationToken cancellationToken)
    {
        // The event carries only the id, so load what the email needs.
        Order? order = await dbContext.Orders.AsNoTracking().FirstOrDefaultAsync(order => order.Id == domainEvent.OrderId, cancellationToken);

        if (order is null)
        {
            return;
        }

        User? user = await dbContext.Users.AsNoTracking().FirstOrDefaultAsync(user => user.Id == order.UserId, cancellationToken);

        if (user is null)
        {
            return;
        }

        string total = order.TotalPrice.Amount.ToString("0.00", CultureInfo.InvariantCulture);

        await emailService.SendAsync(
            user.Email,
            "Your order is placed",
            $"Your order {order.Id.Value} for {total} {order.TotalPrice.Currency.Code} is placed.");
    }
}

IDomainEventHandler<TEvent> is declared in the domain (Task HandleAsync(TEvent domainEvent, CancellationToken cancellationToken)), but the handlers live here because they use IApplicationDbContext and IEmailService. The handler loads the order and the user from the ID in the event, and sends the email. SendWelcomeEmailDomainEventHandler does the same for UserCreatedDomainEvent.

Scrutor already registered them with the handlers. What calls them is Infrastructure: after SaveChangesAsync, it pulls the aggregates’ events and runs the handlers. That’s why the handler can load a saved order. Each event runs in a new DI scope, so the handler gets its own IApplicationDbContext, not the one that saved.

Testing the validators

Validators are plain classes, so their tests need no database and no mocks. They go in a test project, Ecommerce.Application.UnitTests, that references only the Application project:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <IsPackable>false</IsPackable>
    <IsTestProject>true</IsTestProject>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="coverlet.collector">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.NET.Test.Sdk" />
    <PackageReference Include="xunit.v3" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\Ecommerce.Application\Ecommerce.Application.csproj" />
  </ItemGroup>

  <ItemGroup>
    <Using Include="Xunit" />
  </ItemGroup>

</Project>

These are the same packages as the domain tests, so Directory.Packages.props doesn’t change. Add the project to EcommerceApp.slnx with dotnet sln add Ecommerce.Application.UnitTests. Add it to the CA1707 section as well:

[{Ecommerce.Application.UnitTests,Ecommerce.ArchitectureTests,Ecommerce.Domain.UnitTests}/**.cs]

And add this line to the CI test step:

dotnet test --project Ecommerce.Application.UnitTests --no-build --configuration Release

Each test starts from a valid command, changes one field with with, and checks that there is exactly one error, on that field. One small helper does the check:

using FluentValidation.Results;

internal static class ValidationAssert
{
    // Each test changes one field of a valid command, so exactly one error is expected, on that field.
    public static void HasSingleError(ValidationResult result, string propertyName)
    {
        ValidationFailure error = Assert.Single(result.Errors);
        Assert.Equal(propertyName, error.PropertyName);
    }
}

Here are two of the tests for RegisterUserCommandValidator:

using Ecommerce.Application.Users.Register;
using FluentValidation.Results;

public class RegisterUserCommandValidatorTests
{
    private static readonly RegisterUserCommandValidator Validator = new();
    private static readonly RegisterUserCommand ValidCommand = new("Jane", "Doe", "jane@example.com", "password1");

    [Fact]
    public void Validate_Should_ReturnNoErrors_WhenCommandIsValid()
    {
        ValidationResult result = Validator.Validate(ValidCommand);

        Assert.True(result.IsValid);
    }

    [Fact]
    public void Validate_Should_ReturnError_WhenPasswordIsShorterThan8Characters()
    {
        ValidationResult result = Validator.Validate(ValidCommand with { Password = "1234567" });

        ValidationAssert.HasSingleError(result, nameof(RegisterUserCommand.Password));
    }
}

Check it

The Application project builds with only the Domain reference:

dotnet build Ecommerce.Application/Ecommerce.Application.csproj

The architecture tests from Part 1 check that Application doesn’t depend on Infrastructure or the API. They prove that the DbContext interface didn’t break the dependency rule:

dotnet test --project Ecommerce.ArchitectureTests/Ecommerce.ArchitectureTests.csproj

The validator tests run the same way:

dotnet test --project Ecommerce.Application.UnitTests/Ecommerce.Application.UnitTests.csproj

Nothing calls the handlers yet, and there is no database implementation. Because the dependency rule points inward, Application doesn’t wait for them: they depend on it.

The full code at the end of this part is at series-part-3.