ARCHITECTURE

Vertical Slice Architecture vs Clean Architecture: Which One Should You Choose?

Compare Vertical Slice Architecture and Clean Architecture in .NET with real C# examples, trade-offs, project structures, and practical guidance.

30 min readBurak Emre Kadan
All posts
Vertical Slice Architecture versus Clean Architecture in .NET, comparing feature organization and dependency boundaries.

The ticket is short: allow customers to cancel an order. Cancellation is only allowed before shipping, the order's state has to change, and the change has to be saved safely.

In a traditionally layered .NET solution, you start in Api/Controllers/OrdersController.cs. Then Application/Commands/CancelOrderCommand.cs, a handler in Application/Handlers/, a validator, a DTO, the IOrderRepository interface, its implementation in Infrastructure/Repositories/, and finally Domain/Entities/Order.cs, where the rule about shipped orders actually lives. Eight folders for one behavior, each also holding code for every other feature.

In a feature-oriented solution, you open Features/Orders/CancelOrder/ and find the endpoint, request, response, and handler side by side. The Order entity still lives in the domain, but most of the feature fits on one screen.

Neither picture guarantees good architecture. The layered version can be a maze of forwarding calls that protects nothing. The feature folder can be a 300-line endpoint with business rules copied from three other features. Folders are where code lives. Architecture is about what code is allowed to know.

That's the question behind Vertical Slice Architecture vs Clean Architecture: should we organize our application around technical layers, or around the features users actually care about? The short answer is that they solve different problems, and many good .NET codebases use both. This article shows how, with the same feature built three ways in C# 14 and .NET 10.

What Is Clean Architecture?

Clean Architecture, as Robert C. Martin described it in 2012, is a set of rules about dependency direction. Business rules sit at the center. Use cases wrap around them. Delivery mechanisms (HTTP, message queues) and infrastructure (databases, external APIs) sit at the edge.

The Dependency Rule says source-code dependencies point only inward. The domain doesn't reference EF Core, ASP.NET Core, or a payment SDK, and use cases don't reference the web framework that calls them. When an inner layer needs something from outside, it declares an abstraction and the outer layer implements it. That's dependency inversion, and it's the mechanism that makes the rule workable.

Clean Architecture: source-code dependencies

  ┌──────────────┐      ┌──────────────────┐      ┌──────────────┐
  │     Api      │ ───► │   Application    │ ───► │    Domain    │
  │ Minimal APIs │      │ use cases, ports │      │ Order, rules │
  └──────┬───────┘      └────────▲─────────┘      └──────▲───────┘
         │ composition root      │ implements ports      │
         ▼                       │                       │
  ┌──────────────────────────────┴───────────────────────┘
  │ Infrastructure: EF Core, HTTP clients, message brokers
  └──────────────────────────────────────────────────────

Runtime request flow

  HTTP ─► Api ─► Application ─► IOrderRepository ─► Infrastructure ─► PostgreSQL

At runtime, a request flows outward to the database. At compile time, knowledge flows inward: the use case calls the database without knowing it's PostgreSQL.

The benefits are real. Business rules can be unit-tested without a database. Infrastructure can be isolated or replaced without rewriting the rules. A second delivery mechanism, such as a background job that cancels unpaid orders, reuses the same use case.

A project per layer is one way to enforce the rule, not the rule itself. Separate .csproj files let the compiler reject a domain-to-EF-Core reference, but one project with disciplined namespaces and an architecture test can enforce the same boundaries. Microsoft's architecture guide presents the multi-project layout as a common implementation, not the definition.

Explicit boundaries have a cost: every boundary needs an abstraction, and organizing by layer scatters one feature across the solution. I covered that in Is Clean Architecture Making Your .NET Application More Complicated?. It's worth paying when the boundary protects something valuable.

What Is Vertical Slice Architecture?

Vertical Slice Architecture organizes code around individual features or use cases instead of technical responsibilities. Each slice, such as "cancel order" or "get order history," contains what it needs from the HTTP edge to data access. Jimmy Bogard, who popularized the term, summarized the goal in his original article as minimizing coupling between slices and maximizing coupling within a slice.

Vertical Slice Architecture: features cut through the technical concerns

               CreateProduct  GetProduct  PlaceOrder  CancelOrder  GetOrderHistory
               ─────────────  ──────────  ──────────  ───────────  ───────────────
  HTTP           endpoint      endpoint    endpoint    endpoint      endpoint
  Validation     rules         ─           rules       rules         paging
  Logic          domain call   ─           domain      domain        ─
  Data access    DbContext     projection  repository  DbContext     projection
               ─────────────  ──────────  ──────────  ───────────  ───────────────
  Shared:      domain model · DbContext · auth policies · endpoint filters · problem details

The benefits come from locality. When "cancel order" changes, the change usually stays in one folder, and a new developer can read the feature top to bottom. Slices evolve independently: a read-only query can stay a direct EF Core projection while a complex command grows a rich domain model. Dependencies stay focused, because a slice injects only what it uses. Validation and data access fit the feature: GetOrderHistory cares about paging limits, CancelOrder about the reason's length.

Vertical slicing does not mean duplicating everything. The bottom row of the diagram is shared on purpose. Domain invariants belong in the domain model, so every slice that touches an order goes through the same Cancel method. Authentication, error responses, and logging belong in middleware, endpoint filters, and route groups. What a slice owns is its request, response, handler, and the query that fits it.

A good rule: share when two features must stay consistent (a business rule, a security policy). Don't share when they only happen to look alike today (two response DTOs with similar fields).

Traditional Layered Structure vs Feature-Oriented Structure

Take an e-commerce API with five features: Create Product, Get Product, Place Order, Cancel Order, and Get Order History. Here are the two structures side by side.

Layered (organized by technical role)        Feature-oriented (organized by use case)

src/                                         src/
  Api/                                         Api/
    Controllers/                                 Features/
      ProductsController.cs                        Products/
      OrdersController.cs                            CreateProduct/
  Application/                                       GetProduct/
    Commands/                                      Orders/
      CreateProductCommand.cs                        PlaceOrder/
      PlaceOrderCommand.cs                           CancelOrder/
      CancelOrderCommand.cs                            CancelOrder.cs
    Queries/                                         GetOrderHistory/
      GetProductQuery.cs                         Shared/
      GetOrderHistoryQuery.cs                  Domain/
    Handlers/                                    Orders/
    Validators/                                  Products/
  Domain/                                      Infrastructure/
    Entities/                                    Persistence/
    ValueObjects/
  Infrastructure/
    Persistence/
    Repositories/

Both trees can respect the Dependency Rule. In both, Domain can be a separate project that references nothing. The difference is how the application-facing code is grouped.

Concern Layered Feature-oriented
Discoverability Answers "where are the validators?" Answers "what does cancel order do?", the question tickets ask
Change locality One new response field touches several folders Usually one folder
Shared code Sharing is the default, so services grow to forty methods Sharing is deliberate, until someone copies a rule instead of moving it
Coupling Everything in the same technical role Everything about one feature, which tends to change together
Testing No inherent strategy Maps neatly to one integration test class per slice
Team ownership Layer ownership is rare and a bottleneck Teams owning capabilities get a natural boundary
Long-term maintenance Obvious home for every file Needs discipline to keep Shared/ from becoming a junk drawer

Folder count proves nothing. Thirty projects can have tangled dependencies, and one project with three folders can have clean ones.

Real Example: Cancel an Order

Here's the feature built three ways, targeting .NET 10, C# 14, and EF Core 10 with PostgreSQL. The code compiles, and the tests shown later were run against PostgreSQL 17 in a container.

The business rules:

  1. Only an existing order can be cancelled. Unknown IDs return 404.
  2. Shipped or delivered orders cannot be cancelled: 409 Conflict.
  3. Repeated cancellation is idempotent. It succeeds, changes nothing, and returns the original cancellation time, because clients retry on timeouts.
  4. Cancellation records the status, the time, and an optional reason of at most 500 characters.
  5. Concurrent changes are detected with optimistic concurrency, not silently overwritten.

The shared domain model

All three implementations share this domain model, and it has no dependency on EF Core or ASP.NET Core. The rules live in Cancel, not in an endpoint.

namespace Shop.Domain.Orders;

public enum OrderStatus { Pending, Paid, Shipped, Delivered, Cancelled }

public enum CancellationResult
{
    Cancelled,        // the order changed state in this call
    AlreadyCancelled, // repeated request: nothing changes, not an error
    TooLateToCancel   // shipped or delivered: rejected
}

public sealed class Order
{
    public const int MaxCancellationReasonLength = 500;

    private readonly List<OrderLine> _lines = [];

    private Order() { } // for EF Core

    public Guid Id { get; private set; }
    public Guid CustomerId { get; private set; }
    public OrderStatus Status { get; private set; }
    public DateTimeOffset PlacedAt { get; private set; }
    public DateTimeOffset? CancelledAt { get; private set; }
    public string? CancellationReason { get; private set; }
    public IReadOnlyList<OrderLine> Lines => _lines;

    public static Order Place(Guid customerId, IEnumerable<OrderLine> lines, DateTimeOffset now)
    {
        var order = new Order
        {
            Id = Guid.CreateVersion7(now),
            CustomerId = customerId,
            Status = OrderStatus.Pending,
            PlacedAt = ToStoredPrecision(now)
        };

        order._lines.AddRange(lines);
        if (order._lines.Count == 0)
            throw new ArgumentException("An order needs at least one line.", nameof(lines));

        return order;
    }

    public CancellationResult Cancel(string? reason, DateTimeOffset now)
    {
        switch (Status)
        {
            case OrderStatus.Cancelled:
                return CancellationResult.AlreadyCancelled;
            case OrderStatus.Shipped or OrderStatus.Delivered:
                return CancellationResult.TooLateToCancel;
        }

        if (reason?.Length > MaxCancellationReasonLength)
            throw new ArgumentException("Cancellation reason is too long.", nameof(reason));

        Status = OrderStatus.Cancelled;
        CancelledAt = ToStoredPrecision(now);
        CancellationReason = reason;
        return CancellationResult.Cancelled;
    }

    // Timestamps are recorded to the microsecond (PostgreSQL's precision), so the
    // value returned now equals the value read back later.
    private static DateTimeOffset ToStoredPrecision(DateTimeOffset value) =>
        value.AddTicks(-(value.Ticks % TimeSpan.TicksPerMicrosecond));

    // MarkPaid() and MarkShipped() omitted: simple guarded state transitions.
}

Expected outcomes such as "too late" come back as a value, not an exception. A too-long reason still throws, because the API validates it first. Time comes in as a parameter, so tests control it. OrderLine is a plain entity with product, price, and quantity. The persistence mapping (table names, a string conversion for Status, and PostgreSQL's xmin column as a shadow concurrency token, per the Npgsql concurrency docs) lives in an IEntityTypeConfiguration<Order> in Infrastructure.

Implementation A: Clean Architecture

The application layer declares what it needs and knows nothing about HTTP or EF Core. Here the repository abstraction lives in the domain project, next to the aggregate it loads. Putting it in Application is just as valid. What matters is that Infrastructure implements it and nothing inside references Infrastructure.

// Shop.Domain/Orders/IOrderRepository.cs
public interface IOrderRepository
{
    /// <summary>Loads the complete aggregate, including its lines.</summary>
    Task<Order?> GetByIdAsync(Guid id, CancellationToken cancellationToken);

    void Add(Order order);

    /// <exception cref="ConcurrencyConflictException">
    /// Another request changed the order after it was loaded.
    /// </exception>
    Task SaveChangesAsync(CancellationToken cancellationToken);
}

// Shop.Application/Orders/CancelOrder/CancelOrderHandler.cs
namespace Shop.Application.Orders.CancelOrder;

public sealed record CancelOrderCommand(Guid OrderId, string? Reason);

public enum CancelOrderStatus { Cancelled, NotFound, TooLateToCancel, Conflict }

public sealed record CancelOrderResult(CancelOrderStatus Status, DateTimeOffset? CancelledAt = null);

public sealed class CancelOrderHandler(IOrderRepository orders, TimeProvider clock)
{
    public async Task<CancelOrderResult> HandleAsync(CancelOrderCommand command, CancellationToken cancellationToken)
    {
        var order = await orders.GetByIdAsync(command.OrderId, cancellationToken);
        if (order is null)
            return new(CancelOrderStatus.NotFound);

        var result = order.Cancel(command.Reason, clock.GetUtcNow());
        if (result == CancellationResult.TooLateToCancel)
            return new(CancelOrderStatus.TooLateToCancel);

        if (result == CancellationResult.Cancelled)
        {
            try
            {
                await orders.SaveChangesAsync(cancellationToken);
            }
            catch (ConcurrencyConflictException)
            {
                return new(CancelOrderStatus.Conflict);
            }
        }

        // Cancelled now or earlier: both are a successful outcome for the caller.
        return new(CancelOrderStatus.Cancelled, order.CancelledAt);
    }
}

Infrastructure implements the port with EF Core and translates EF Core's exception into the domain's own:

// Shop.Infrastructure/Persistence/OrderRepository.cs
internal sealed class OrderRepository(ShopDbContext db) : IOrderRepository
{
    public Task<Order?> GetByIdAsync(Guid id, CancellationToken cancellationToken) =>
        db.Orders
            .Include(o => o.Lines)
            .SingleOrDefaultAsync(o => o.Id == id, cancellationToken);

    public void Add(Order order) => db.Orders.Add(order);

    public async Task SaveChangesAsync(CancellationToken cancellationToken)
    {
        try
        {
            await db.SaveChangesAsync(cancellationToken);
        }
        catch (DbUpdateConcurrencyException ex)
        {
            throw new ConcurrencyConflictException("The order was changed by another request.", ex);
        }
    }
}

The Minimal API endpoint is a thin adapter that turns HTTP into a command and the result into HTTP. Request validation uses .NET 10's built-in Minimal API validation, switched on with builder.Services.AddValidation():

// Shop.Api/Endpoints/OrderEndpoints.cs
public sealed record CancelOrderRequest([MaxLength(Order.MaxCancellationReasonLength)] string? Reason);

public sealed record CancelOrderResponse(Guid OrderId, string Status, DateTimeOffset CancelledAt);

public static class OrderEndpoints
{
    public static IEndpointRouteBuilder MapOrderEndpoints(this IEndpointRouteBuilder app)
    {
        app.MapPost("/orders/{orderId:guid}/cancel", CancelOrder);
        return app;
    }

    private static async Task<Results<Ok<CancelOrderResponse>, NotFound, ProblemHttpResult>> CancelOrder(
        Guid orderId,
        CancelOrderRequest request,
        CancelOrderHandler handler,
        CancellationToken cancellationToken)
    {
        var result = await handler.HandleAsync(new CancelOrderCommand(orderId, request.Reason), cancellationToken);

        return result.Status switch
        {
            CancelOrderStatus.Cancelled =>
                TypedResults.Ok(new CancelOrderResponse(orderId, "Cancelled", result.CancelledAt!.Value)),
            CancelOrderStatus.NotFound =>
                TypedResults.NotFound(),
            CancelOrderStatus.TooLateToCancel =>
                TypedResults.Problem("Shipped orders cannot be cancelled.", statusCode: StatusCodes.Status409Conflict),
            CancelOrderStatus.Conflict =>
                TypedResults.Problem("The order was changed by another request. Retry.", statusCode: StatusCodes.Status409Conflict),
            _ => throw new UnreachableException()
        };
    }
}

The dependency flow is Api → Application → Domain ← Infrastructure. Program.cs is the composition root: TimeProvider.System as a singleton, ShopDbContext, OrderRepository, and the handler as scoped (more on why in the post on DbContext lifetimes).

Which abstractions earn their keep? IOrderRepository guarantees the aggregate is loaded whole and turns an EF Core exception into a concept the application understands. TimeProvider makes time controllable in tests. CancelOrderResult lets a non-HTTP caller reuse the handler; if you never have one, it's ceremony. Each abstraction should be able to name what it protects.

Implementation B: Vertical Slice Architecture

The same feature as one file in Features/Orders/CancelOrder/. The endpoint, request, response, and handler are together, and the handler uses ShopDbContext directly.

// Shop.Api/Features/Orders/CancelOrder/CancelOrder.cs
namespace Shop.Api.Features.Orders.CancelOrder;

public sealed record CancelOrderRequest([MaxLength(Order.MaxCancellationReasonLength)] string? Reason);

public sealed record CancelOrderResponse(Guid OrderId, string Status, DateTimeOffset CancelledAt);

public static class CancelOrderEndpoint
{
    public static void Map(IEndpointRouteBuilder app) =>
        app.MapPost("/orders/{orderId:guid}/cancel", HandleAsync)
           .WithName("CancelOrder")
           .WithTags("Orders");

    public static async Task<Results<Ok<CancelOrderResponse>, NotFound, ProblemHttpResult>> HandleAsync(
        Guid orderId,
        CancelOrderRequest request,
        ShopDbContext db,
        TimeProvider clock,
        CancellationToken cancellationToken)
    {
        // Cancellation doesn't depend on the lines, so this slice doesn't load them.
        var order = await db.Orders.SingleOrDefaultAsync(o => o.Id == orderId, cancellationToken);
        if (order is null)
            return TypedResults.NotFound();

        var result = order.Cancel(request.Reason, clock.GetUtcNow());
        if (result == CancellationResult.TooLateToCancel)
            return TypedResults.Problem("Shipped orders cannot be cancelled.", statusCode: StatusCodes.Status409Conflict);

        if (result == CancellationResult.Cancelled)
        {
            try
            {
                await db.SaveChangesAsync(cancellationToken);
            }
            catch (DbUpdateConcurrencyException)
            {
                return TypedResults.Problem("The order was changed by another request. Retry.", statusCode: StatusCodes.Status409Conflict);
            }
        }

        return TypedResults.Ok(new CancelOrderResponse(order.Id, "Cancelled", order.CancelledAt!.Value));
    }
}

Program.cs calls CancelOrderEndpoint.Map(app). There's no handler class to register, because Minimal APIs inject ShopDbContext and TimeProvider straight into the handler method.

Architecturally, this handler is application logic and a persistence adapter merged into one unit. That's a deliberate trade. It depends on EF Core at compile time: it names ShopDbContext and catches DbUpdateConcurrencyException. Testing it means a real database, which, as you'll see, is a good idea anyway. In return, it loads exactly what the feature needs (one row, no lines) and has no forwarding layers.

What it doesn't do is decide the business rule. The status check is still order.Cancel. That's the line between a healthy slice and a transaction script in a nice folder.

Implementation C: Hybrid Architecture

The hybrid keeps the feature-oriented organization of B and the enforced boundaries of A, and applies each where it pays off. The projects:

src/
  Shop.Domain/            no package references (enforced by the compiler and a test)
    Orders/  Order.cs, IOrderRepository.cs
  Shop.Infrastructure/    references Domain + Npgsql.EntityFrameworkCore.PostgreSQL
    Persistence/  ShopDbContext.cs, OrderConfiguration.cs, OrderRepository.cs
  Shop.Api/               references Domain + Infrastructure
    Features/Orders/CancelOrder/CancelOrder.cs
    Features/Orders/GetOrderHistory/GetOrderHistory.cs
    Program.cs            composition root

Write slices that change an aggregate go through IOrderRepository, because several of them (place, cancel, ship) need the same guarantees: a whole aggregate, and conflicts as a domain exception. Read slices query ShopDbContext directly, because a read has no invariant to protect.

// Shop.Api/Features/Orders/CancelOrder/CancelOrder.cs (request and response records as in B)
public sealed class CancelOrderHandler(IOrderRepository orders, TimeProvider clock)
{
    public async Task<Results<Ok<CancelOrderResponse>, NotFound, ProblemHttpResult>> HandleAsync(
        Guid orderId, CancelOrderRequest request, CancellationToken cancellationToken)
    {
        var order = await orders.GetByIdAsync(orderId, cancellationToken);
        if (order is null)
            return TypedResults.NotFound();

        // Same flow as B, with orders.SaveChangesAsync and ConcurrencyConflictException
        // in place of db.SaveChangesAsync and DbUpdateConcurrencyException.
        // ...
    }
}

public static class CancelOrderEndpoint
{
    public static void Map(IEndpointRouteBuilder app) =>
        app.MapPost("/orders/{orderId:guid}/cancel",
                (Guid orderId, CancelOrderRequest request, CancelOrderHandler handler, CancellationToken ct) =>
                    handler.HandleAsync(orderId, request, ct))
           .WithName("CancelOrder")
           .WithTags("Orders");
}

// Program.cs
builder.Services.AddProblemDetails();
builder.Services.AddValidation();
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddPersistence(builder.Configuration.GetConnectionString("Shop")
    ?? throw new InvalidOperationException("Connection string 'Shop' is missing."));
builder.Services.AddScoped<CancelOrderHandler>();

One pragmatic choice: the handler returns HTTP result types. It lives in the Api project, so that coupling is allowed, and it saves a mapping layer. The day a message consumer also needs to cancel orders, split it into Implementation A's shape. That refactoring stays inside one folder.

How the three requests flow

A. Clean Architecture
   POST /orders/{id}/cancel
     └─► OrderEndpoints.CancelOrder          (Api: HTTP ⇄ command/result)
          └─► CancelOrderHandler             (Application)
               ├─► IOrderRepository          (port, declared inside)
               │    └─► OrderRepository ─► ShopDbContext ─► PostgreSQL   (Infrastructure)
               └─► Order.Cancel              (Domain: the rule)

B. Vertical Slice
   POST /orders/{id}/cancel
     └─► CancelOrderEndpoint.HandleAsync     (Features/Orders/CancelOrder)
          ├─► ShopDbContext ─► PostgreSQL    (direct, intentional coupling)
          └─► Order.Cancel                   (Domain: the rule)

C. Hybrid
   POST /orders/{id}/cancel
     └─► CancelOrderEndpoint ─► CancelOrderHandler   (Features/Orders/CancelOrder)
          ├─► IOrderRepository ─► OrderRepository ─► PostgreSQL
          └─► Order.Cancel                           (Domain: the rule)

All three call the same Order.Cancel. Only where the code lives and what it may reference differ.

The Dependency Rule Still Matters in Vertical Slices

Feature folders enforce nothing. If Shop.Api references Shop.Infrastructure, every feature can use ShopDbContext and anything else Infrastructure exposes. A folder is a convention. A compile-time reference is a permission.

That's why the hybrid gives the domain its own project: the compiler rejects EF Core there. A small test keeps it that way:

[Fact]
public void Domain_does_not_reference_infrastructure_or_aspnetcore()
{
    var references = typeof(Order).Assembly.GetReferencedAssemblies().Select(a => a.Name!);

    Assert.DoesNotContain(references, name =>
        name.StartsWith("Microsoft.EntityFrameworkCore", StringComparison.Ordinal) ||
        name.StartsWith("Microsoft.AspNetCore", StringComparison.Ordinal) ||
        name.StartsWith("Npgsql", StringComparison.Ordinal));
}

The valid dependency directions in the hybrid:

Hybrid architecture: compile-time references

  ┌────────────────────────────────────────────────────────┐
  │ Shop.Api                                               │
  │   Features/Orders/CancelOrder     ──► IOrderRepository │──┐
  │   Features/Orders/GetOrderHistory ──► ShopDbContext    │──┼──┐
  │   Common/ (filters, problem details, auth policies)    │  │  │
  │   Program.cs (composition root: wires ports to impls)  │  │  │
  └────────────────────────────────────────────────────────┘  │  │
                                                              ▼  │
  ┌────────────────────────────┐   implements   ┌────────────────┴─────┐
  │ Shop.Domain                │ ◄───────────── │ Shop.Infrastructure  │
  │   Order, OrderLine, rules  │                │   ShopDbContext      │
  │   IOrderRepository (port)  │                │   OrderRepository    │
  │   no package references    │                │   EF Core, Npgsql    │
  └────────────────────────────┘                └──────────────────────┘

  Allowed:   Api → Domain, Api → Infrastructure, Infrastructure → Domain
  Forbidden: Domain → anything, Infrastructure → Api

Runtime dependency injection is a separate concern. Program.cs decides that IOrderRepository resolves to OrderRepository per request. DI doesn't create boundaries. It connects the ones the project references allow.

When feature code depends directly on infrastructure, things can go wrong: business rules leak into handlers because the entity is right there, queries get copied with small differences, a PostgreSQL-specific operator spreads into fifty files, and there's no seam left for a fake. None of these is a disaster when it's chosen. They hurt when they happen by accident.

So separate intentional coupling from accidental coupling. GetOrderHistory using EF Core is intentional: the team decided reads may use the DbContext, and the domain is protected anyway. A handler that re-implements the "can this order be cancelled" check because nobody looked for Order.Cancel is accidental. The first is a decision. The second is drift.

CQRS and MediatR: Required or Optional?

CQRS means using different models for changing state and for reading it. Martin Fowler's description covers a spectrum, from queries projecting straight into DTOs while commands use the domain model, to a separate read store kept up to date by events. He also warns that for most systems, CQRS adds risky complexity.

Our examples sit at the light end: CancelOrder goes through the aggregate, GetOrderHistory projects straight into DTOs. Same database, different models.

Four things are worth separating. Vertical Slice Architecture doesn't require CQRS: a slice is a unit of organization, even if most end up command- or query-shaped. CQRS doesn't require MediatR: one is a modeling decision, the other an in-process dispatcher. Clean Architecture doesn't require MediatR either: a use case can be a plain class called directly. And separate command and query classes aren't a distributed system. Two folders hitting the same tables is light CQRS at most.

Here's direct handler invocation without a mediator, from the hybrid:

builder.Services.AddScoped<CancelOrderHandler>();

app.MapPost("/orders/{orderId:guid}/cancel",
    (Guid orderId, CancelOrderRequest request, CancelOrderHandler handler, CancellationToken ct) =>
        handler.HandleAsync(orderId, request, ct));

"Go to Definition" on HandleAsync lands on the handler. The compiler checks the call. There's no assembly scanning.

Mediator pipelines earn their place when many handlers need the same behavior and are called from more than one entry point: transactions, outbox writes, or auditing applied uniformly to HTTP requests, message consumers, and jobs. For HTTP-only concerns, ASP.NET Core already has endpoint filters and middleware, applied per route group. MediatR also moved to a commercial license in 2025, with a free tier for smaller organizations. Pick it for the pipeline, not out of habit.

EF Core in Vertical Slice Architecture

Using the DbContext directly is the most debated part of vertical slicing. Here's the read slice from the hybrid, which also works unchanged in a pure vertical slice codebase:

// Shop.Api/Features/Orders/GetOrderHistory/GetOrderHistory.cs
namespace Shop.Api.Features.Orders.GetOrderHistory;

public sealed record OrderHistoryItem(Guid OrderId, DateTimeOffset PlacedAt, string Status, int ItemCount, decimal Total);

public sealed record OrderHistoryPage(IReadOnlyList<OrderHistoryItem> Items, int Page, int PageSize);

public static class GetOrderHistory
{
    public const int MaxPageSize = 50;

    public static void Map(IEndpointRouteBuilder app) =>
        app.MapGet("/customers/{customerId:guid}/orders", HandleAsync)
           .WithName("GetOrderHistory")
           .WithTags("Orders");

    public static async Task<Ok<OrderHistoryPage>> HandleAsync(
        Guid customerId,
        ShopDbContext db,
        CancellationToken cancellationToken,
        int page = 1,
        int pageSize = 20)
    {
        page = Math.Max(page, 1);
        pageSize = Math.Clamp(pageSize, 1, MaxPageSize);

        var items = await db.Orders
            .AsNoTracking()
            .Where(o => o.CustomerId == customerId)
            .OrderByDescending(o => o.PlacedAt)
            .ThenBy(o => o.Id)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .Select(o => new OrderHistoryItem(
                o.Id,
                o.PlacedAt,
                o.Status.ToString(),
                o.Lines.Sum(l => l.Quantity),
                o.Lines.Sum(l => l.UnitPrice * l.Quantity)))
            .ToListAsync(cancellationToken);

        return TypedResults.Ok(new OrderHistoryPage(items, page, pageSize));
    }
}

Query composition. Filter, order, page, and projection run as one query, and the sums over Lines are computed in SQL, so no line entities are loaded. A repository method returning entities would make that harder to get right.

Projection and AsNoTracking. Only the columns the response needs are selected; internal fields such as the cancellation reason never leave the database. Because the query returns no entity instances, EF Core wouldn't track anything anyway. AsNoTracking is redundant here, but it marks the read path and stays correct if someone later returns an entity. ThenBy(o => o.Id) keeps paging stable when two orders share a timestamp.

Change tracking and transactions. On the write side, tracking is what you want: load, call Cancel, SaveChangesAsync. A single SaveChangesAsync runs in a transaction, which covers one aggregate per request. When a slice spans several saves or raw SQL, use db.Database.BeginTransactionAsync, inside the execution strategy if retries are enabled. Optimistic concurrency is covered in the EF Core concurrency docs.

Persistence coupling. The slice knows EF Core and the schema shape. For reads, that's usually fine: a read model is about data shape. For writes, check that no rule has slipped out of the domain.

Direct DbContext Specific repository
Query shape Exactly what the feature needs What the repository offers
Aggregate integrity Up to each slice Enforced in one place
EF Core features All available Hidden unless exposed
Exception translation Per slice Centralized
Testing Real database Fakes for handlers, real database for the repository
Typical fit Reads, simple writes Rich aggregates written by several slices

Neither column wins everywhere, a trade-off I explore in more depth in Stop Using the Repository Pattern With EF Core (Unless You Need It). In our feature, the repository always includes Lines, so the hybrid's cancel query joins order_lines while the pure slice reads one row. Trivial here, maybe not on a hot path.

Testing Both Architectures

Boundaries make testing possible, not useful. A handler forwarding to a mocked repository can have full coverage and miss every bug. Test where the risk lives.

Domain unit tests are cheap and identical in every architecture:

[Fact]
public void Cancel_twice_is_a_no_op_that_keeps_the_original_timestamp()
{
    var order = TestOrders.Pending();
    order.Cancel("First", TestOrders.Now.AddHours(1));

    var result = order.Cancel("Second", TestOrders.Now.AddHours(2));

    Assert.Equal(CancellationResult.AlreadyCancelled, result);
    Assert.Equal(TestOrders.Now.AddHours(1), order.CancelledAt);
    Assert.Equal("First", order.CancellationReason);
}

Application handler tests are where ports pay off. A hand-written fake is often clearer than a mocking library, and FakeTimeProvider controls time:

internal sealed class InMemoryOrderRepository : IOrderRepository
{
    private readonly Dictionary<Guid, Order> _orders = [];
    public int SaveCount { get; private set; }

    public Task<Order?> GetByIdAsync(Guid id, CancellationToken cancellationToken) =>
        Task.FromResult(_orders.GetValueOrDefault(id));

    public void Add(Order order) => _orders[order.Id] = order;

    public Task SaveChangesAsync(CancellationToken cancellationToken)
    {
        SaveCount++;
        return Task.CompletedTask;
    }
}

[Fact]
public async Task Repeated_cancellation_succeeds_and_saves_once()
{
    var order = TestOrders.Pending();
    _orders.Add(order);
    var handler = new CancelOrderHandler(_orders, _clock);
    var command = new CancelOrderCommand(order.Id, "Duplicate order");

    var first = await handler.HandleAsync(command, TestContext.Current.CancellationToken);
    _clock.Advance(TimeSpan.FromMinutes(5));
    var second = await handler.HandleAsync(command, TestContext.Current.CancellationToken);

    Assert.Equal(CancelOrderStatus.Cancelled, first.Status);
    Assert.Equal(CancelOrderStatus.Cancelled, second.Status);
    Assert.Equal(first.CancelledAt, second.CancelledAt);
    Assert.Equal(1, _orders.SaveCount);
}

API and database integration tests cover what fakes can't: SQL translation, concurrency tokens, serialization, validation, status codes. The EF Core testing guidance recommends your production database system where possible. Testcontainers gives each test class a disposable PostgreSQL, and WebApplicationFactory hosts the API in memory:

public sealed class PostgresFixture : IAsyncLifetime
{
    private readonly PostgreSqlContainer _container = new PostgreSqlBuilder("postgres:17-alpine").Build();

    public string ConnectionString => _container.GetConnectionString();

    public ShopDbContext CreateDbContext() =>
        new(new DbContextOptionsBuilder<ShopDbContext>().UseNpgsql(ConnectionString).Options);

    public async ValueTask InitializeAsync()
    {
        await _container.StartAsync();
        await using var db = CreateDbContext();
        await db.Database.EnsureCreatedAsync(); // real projects: apply migrations here
    }

    public ValueTask DisposeAsync() => _container.DisposeAsync();
}

public class CancelOrderApiTests(PostgresFixture postgres) : IClassFixture<PostgresFixture>
{
    private readonly HttpClient _client = new WebApplicationFactory<Program>()
        .WithWebHostBuilder(builder => builder.UseSetting("ConnectionStrings:Shop", postgres.ConnectionString))
        .CreateClient();

    [Fact]
    public async Task Cancelling_twice_returns_the_same_result()
    {
        var ct = TestContext.Current.CancellationToken;
        var orderId = await SeedAsync(TestOrders.Pending());

        var first = await _client.PostAsJsonAsync($"/orders/{orderId}/cancel", new { reason = "Ordered by mistake" }, ct);
        var second = await _client.PostAsJsonAsync($"/orders/{orderId}/cancel", new { reason = "Retry" }, ct);

        Assert.Equal(HttpStatusCode.OK, first.StatusCode);
        Assert.Equal(HttpStatusCode.OK, second.StatusCode);
        var a = await first.Content.ReadFromJsonAsync<CancelOrderResponse>(ct);
        var b = await second.Content.ReadFromJsonAsync<CancelOrderResponse>(ct);
        Assert.Equal(a!.CancelledAt, b!.CancelledAt);
    }

    // SeedAsync, plus tests for 409 on shipped orders, 404 on unknown IDs,
    // and 400 for a 501-character reason, omitted for brevity.
}

This test caught a real bug while I was preparing the article; the handler test above did not. The first response returned CancelledAt from memory, with .NET's 100-nanosecond precision. The second read it back from PostgreSQL, whose timestamps have microsecond resolution. The values differed in the seventh decimal place, so the "idempotent" endpoint gave two different answers. The fake repository never rounds anything, so it couldn't see this. The fix was ToStoredPrecision in the domain model. Finding it took a real database.

That's also how to test a vertical slice without mocking everything: call the handler directly with a real ShopDbContext pointed at the container, or go through HTTP. Seed, act, assert on the response and the database. No mocked DbSet, no in-memory provider pretending to be PostgreSQL. Another test in the suite loads the same order in two DbContexts and confirms the xmin token turns the second save into a ConcurrencyConflictException, which again only a real database can show.

A balanced suite for either architecture: many domain tests, a few handler tests where ports exist and the orchestration branches, and an integration test class per slice.

Where Vertical Slice Architecture Works Well

Feature-rich business applications. Back-office systems and SaaS products have hundreds of use cases with moderate rules. Feature folders keep each one findable, and most changes stay local.

APIs with independently evolving use cases. When GetOrderHistory needs a new filter, CancelOrder shouldn't be at risk. Slices make that independence the default.

Modular monoliths. Slices group naturally into modules (Orders, Catalog, Payments), and modules are where hard boundaries go: separate schemas, explicit contracts, no cross-module DbContext access.

Products with frequent feature changes. If the roadmap shifts every sprint, the cost that matters is changing one feature. Deleting a feature means deleting a folder.

Teams organized around business capabilities. A team that owns checkout owns Features/Checkout/, and reviews happen in a few files.

The common thread: the unit of change is the feature, so the unit of organization should be too.

Where Clean Architecture Works Well

Complex business domains. In insurance rating, tax engines, or clinical workflows, the rules are the product. Isolating them from frameworks keeps them testable for years.

Long-lived enterprise applications. Frameworks change over a fifteen-year lifetime. Code that doesn't reference them doesn't have to change with them.

Multiple delivery mechanisms. When the same use case runs from an API, a message consumer, and a scheduled job, use cases that know nothing about HTTP pay off immediately.

Important infrastructure boundaries. Payment providers and legacy or regulatory integrations are volatile. Ports and adapters contain that volatility.

Strict domain isolation requirements. Some organizations need the domain model reviewable or reusable without infrastructure code.

The cost is more projects, more abstractions, slower navigation, and a steeper onboarding curve. Not every enterprise application needs strict layering: a long-lived system that's mostly CRUD gets most of the benefit from a protected domain project and feature folders.

Where Both Approaches Can Fail

Vertical Slice Architecture mistakes

Duplicating business rules. Two slices each check Status != Shipped. Then a "partially shipped" state arrives and only one check gets updated. Fix: when two slices enforce a rule, it moves into the domain model.

Excessive isolation. "Slices never share code" produces five copies of pagination logic and four error formats. Fix: share technical building blocks deliberately. Isolation is about business logic.

Ignoring invariants. Slices set order.Status directly because the setter is public. Fix: private setters and behavior methods, as in Order above.

Inconsistent cross-cutting behavior. One slice returns ProblemDetails, another a string, a third forgets authorization. Fix: route groups with RequireAuthorization, shared endpoint filters, AddProblemDetails, and a test that every endpoint has a policy.

Treating every feature as a subsystem. Fix: a slice is a use case, not a microservice. Modules are the level for hard independence.

Clean Architecture mistakes

Pass-through layers. Handler calls service calls repository, one line each. Fix: remove layers that make no decision.

Unnecessary interfaces. IOrderMapper with one implementation, forever. Fix: interfaces for real boundaries, real variation, or non-deterministic dependencies.

Generic repositories. IRepository<T> hides Include, projections, and AsNoTracking. Fix: specific repositories for aggregates, direct queries for reads, as Microsoft's persistence guidance also suggests.

Excessive mapping. Entity to DTO to response, all with identical fields. Fix: one model per real difference in shape or audience.

Confusing folders with architecture. Four projects, but the domain reaches EF Core through a shared "Common" project. Fix: check the reference graph, not the solution explorer.

Every pattern for CRUD. A command, handler, validator, and repository to read a product by ID. Fix: let simple features be simple, which is where both styles agree.

Performance: Does Architecture Matter?

Neither style is inherently faster. Latency in a typical .NET API is dominated by database round trips, network calls, and serialization. An extra method call, interface dispatch, or scoped service resolution is small next to a network query. I haven't benchmarked these implementations, and I'd distrust any benchmark that ranks architectures without showing the queries.

Architecture influences performance indirectly, through how easy it is to write the right query. A slice that owns its query can project only needed columns, page in SQL, or drop to raw SQL for a hot path, in one place. A generic repository returning entities pushes you toward over-fetching. Our example shows it: the repository's cancel path joins order lines that cancellation never reads.

Likewise, a mediator pipeline with transaction behavior runs on every request, reads included, while endpoint filters run only on their route groups. Caching, such as output caching or HybridCache, fits either style.

Architecture decides how easy it is to optimize. Queries decide how fast it runs. Measure before blaming either.

A Practical Decision Matrix

Factor Traditional layered Clean Architecture Vertical Slice Architecture Hybrid: Clean boundaries + vertical slices
Domain complexity Best for high complexity throughout Best for low to moderate, varies per slice Moderate to high, concentrated in some areas
Feature independence Low: features spread across layers High High
Team size Larger teams with established conventions Small to medium teams, or feature teams Any; scales into modules
Change frequency Lower, deliberate change High, feature-local change High at the edges, deliberate in the domain
Integration complexity Many volatile integrations behind ports Few integrations Ports only for the volatile ones
Testing strategy Unit tests per layer with fakes Integration tests per slice Domain unit tests + integration tests per slice
Dependency isolation Strong, compiler-enforced Weak unless enforced separately Strong for the domain, intentional coupling elsewhere
Maintainability Predictable, but slow for small changes Fast locally, risk of duplicated rules Fast locally, protected core
Initial development cost Highest Lowest Low to moderate

This is guidance, not a scoring system. Domain complexity isn't uniform: checkout can be complex while CMS pages are trivial. Read the matrix per module, and weight factors by what actually hurts in your codebase.

For many feature-rich .NET business applications, my default is the hybrid:

Organize use cases by feature. Keep important invariants in a domain project that references no infrastructure. Use Minimal APIs where they fit. Use EF Core directly where the coupling is acceptable, which means most reads and simple writes, and add repositories where they protect a real boundary. Call handlers directly, and adopt a mediator only for a concrete cross-cutting need. Centralize cross-cutting concerns in route groups, endpoint filters, and middleware. Test persistence against the real database engine. Extract modules when business boundaries become clear, not before.

A realistic structure for a growing application:

src/
  Shop.Api/
    Program.cs                      composition root
    Common/                         endpoint filters, problem details, auth policies
    Features/
      Catalog/
        CreateProduct/  GetProduct/  SearchProducts/
      Orders/
        PlaceOrder/  CancelOrder/  GetOrderHistory/  ShipOrder/
      Payments/
        CapturePayment/  RefundPayment/
  Shop.Domain/
    Catalog/                        Product, Price
    Orders/                         Order, OrderLine, IOrderRepository
    Payments/                       IPaymentGateway (port)
  Shop.Infrastructure/
    Persistence/                    ShopDbContext, configurations, migrations, OrderRepository
    Payments/                       PaymentGatewayClient : IPaymentGateway
tests/
  Shop.Domain.Tests/                fast unit tests for rules
  Shop.Api.IntegrationTests/        Testcontainers + WebApplicationFactory, one class per slice

Ports that Infrastructure implements live in Shop.Domain here. If you'd rather keep use-case-level interfaces out of the domain, add a thin Shop.Application project for them. That's a reasonable choice, not a requirement.

When should this change? Go stricter Clean Architecture when the domain is complex throughout, several delivery mechanisms share use cases, or compliance requires enforced isolation. Go plain vertical slices (one project, no repositories) for small services and internal tools. Go modular monolith when teams start colliding inside Features/: each module gets its own features, domain, and schema, behind explicit contracts.

How to Migrate From Layered Architecture to Vertical Slices

Rewrites stop delivery and bet everything on getting the new structure right the first time. Migrate one feature at a time instead, shippable after every step.

  1. Identify feature boundaries. List use cases from your endpoints and group them by capability. That's your future Features/ tree.
  2. Select a low-risk feature. Good test coverage, few dependencies, low traffic. A read endpoint is a good first candidate.
  3. Map existing dependencies. Trace every class the feature touches, and note which are shared.
  4. Preserve domain invariants. If a rule lives in the service you're about to remove, move it into the entity first, in its own commit.
  5. Move feature-specific code together. Request, response, validator, and handler go into the feature folder. Shared code stays put for now.
  6. Remove pass-through abstractions. Collapse service-to-repository-to-DbContext chains for this feature only. Shared services stay until their last caller moves.
  7. Preserve transaction boundaries. Keep the same SaveChangesAsync points, so what commits together doesn't change.
  8. Add characterization and integration tests. Before moving, capture status codes, bodies, and database state against a real database. They must pass unchanged afterward. Fix odd behavior separately.
  9. Repeat incrementally. Layered and sliced code coexist fine. Delete each shared service when its last caller is gone.

The safety rule: never move code and change behavior in the same step.

Frequently Asked Questions

Is Vertical Slice Architecture better than Clean Architecture?

Neither is better in general, because they answer different questions: how to organize code (by feature) versus which way dependencies point (toward the business rules). For feature-rich applications with moderate domain complexity, slices with a protected domain model are often the better default. For complex domains with many integrations, Clean Architecture's boundaries earn their cost.

Can I combine Vertical Slice Architecture with Clean Architecture?

Yes. Organize application code by feature, keep the domain in a project with no infrastructure references, and put ports in front of volatile infrastructure. The hybrid in this article is one way to do it.

Does Vertical Slice Architecture require MediatR?

No. A slice can be a static method mapped by a Minimal API, or a handler class injected into the endpoint. MediatR helps when many handlers and entry points share a pipeline, and it now requires a commercial license for larger organizations.

Should I use repositories in Vertical Slice Architecture?

Where they protect something: complete aggregates for writes shared by several slices, exception translation, or complex persistence. For reads, a direct EF Core projection is clearer and more efficient. A generic IRepository<T> rarely helps (more on that here).

Is Vertical Slice Architecture suitable for microservices?

Yes. Services are small and feature-focused, which suits slicing. Between services you still need explicit contracts, but that's a service boundary, not a slice boundary. A modular monolith built from slices also makes extracting a service later easier.

Can I migrate an existing Clean Architecture application?

Yes, incrementally. Keep the domain project, reorganize the Application layer by feature, collapse pass-through services one feature at a time, and back each step with integration tests. You'll usually end up with the hybrid, which is usually the right outcome.

Final Thoughts

Here's a simplification that holds up well in practice: Clean Architecture helps you decide which dependencies should exist. Vertical Slice Architecture helps you decide where related code should live.

It isn't a complete definition of either. Clean Architecture says plenty about use cases, and vertical slicing has opinions about coupling. But it explains why they're presented as rivals when they mostly aren't: one is about the direction of arrows, the other about the shape of folders. You can get both right at once.

Whatever you choose, good architecture does two things. It protects the business rules, so Order.Cancel is the only place that decides whether an order can be cancelled. And it keeps feature development understandable, so the next developer can find, change, and test a feature without touring the whole solution.

Would you choose Clean Architecture, Vertical Slice Architecture, or a combination of both for your next .NET project?

References

NEWSLETTER

Get the next one in your inbox

Weekly .NET + AI tips, the source code from every video, and early access to the course.

You'll get weekly .NET + AI tips. Unsubscribe anytime.