Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 7 · Lesson 61 · 7 min read

Clean Architecture vs Vertical Slice in .NET

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Solution Layout, a Slice and a Rule That Fails the Build
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Compare layered, clean (hexagonal) and vertical slice architectures, apply the dependency rule so business logic does not depend on infrastructure, choose a pragmatic structure for a growing .NET API, and enforce architectural boundaries with automated tests.

Concept Explanation

Every application has an architecture whether or not anyone designed it. The classic layered style separates presentation, business logic, and data access into horizontal layers, each depending on the one below. It is simple and familiar, but in practice the business layer ends up depending on the data layer and its ORM, so logic becomes entangled with persistence details, and a feature such as moving a task is spread across a controller, a service, a repository, and a model in four different folders. Changing a feature means touching every layer, and reading it means jumping between them.

Clean architecture, along with its relatives, Alistair Cockburn's hexagonal architecture from 2005, also called ports and adapters, and Jeffrey Palermo's onion architecture from 2008, inverts the key dependency. The domain model and application rules sit in the center and depend on nothing. Infrastructure such as the database, message broker, email service, and web framework sits at the edge and depends inward, implementing interfaces the core defines. The dependency rule states that source code dependencies point only inward. The payoff is that business rules can be tested without a database, and that technology choices, like swapping SQL Server for another store or one queue for another, are contained in adapters. You have already used this idea in the INoteStore interface.

Vertical slice architecture, popularized in the .NET world by Jimmy Bogard around 2018, organizes code by feature rather than by layer. Each slice, such as MoveTask or InviteMember, contains everything it needs: the endpoint, request and response types, validation, the handler logic, and its data access, in one folder. Slices share little, and each can choose its own approach, using a full domain model where the rules are complex and a direct query where they are simple. Change is local, because a feature's code lives together, and this suits teams that ship features continuously. The risk is duplication and inconsistent decisions, which shared building blocks and conventions manage.

You do not have to pick one. A pragmatic structure that works well for many products is a modular monolith with vertical slices for features, a small rich domain layer for the parts with genuine business rules, and infrastructure behind interfaces only where it buys you something, such as time, email, and payment providers. Avoid the failure modes at both extremes: architecture theater, where a simple CRUD screen passes through five projects and ten interfaces, and the big ball of mud, where anything can call anything. Whichever structure you choose, write the rules down and enforce them mechanically with architecture tests that fail the build when a domain class references the infrastructure namespace. From a security view, clear boundaries also give you clear places to put authorization and validation: at every slice entry point, before any logic runs.

StyleOrganizes code byStrengthRisk
LayeredTechnical layerFamiliar, simpleLogic entangled with persistence, scattered features
Clean, hexagonal, onionDependency directionTestable core, swappable infrastructureOver-abstraction for simple features
Vertical sliceFeatureLocal change, readable, fast to shipDuplication, inconsistent choices
Modular monolithBusiness moduleClear boundaries with one deploymentNeeds discipline to keep modules separate
Architecture testsAutomated rulesBoundaries do not erodeRules need maintenance

Worked Example: A Solution Layout, a Slice and a Rule That Fails the Build

The tree shows a pragmatic structure. The slice file keeps one feature together, and the test enforces that the domain does not depend on infrastructure.

Code
src/
  TaskBoard.Domain/            # entities, value objects, domain rules. References nothing.
    Tasks/TaskItem.cs
    Projects/Project.cs
  TaskBoard.Application/       # slices, the EF Core DbContext, and abstractions the outside must implement
    Features/
      Tasks/MoveTask.cs        # endpoint + request + validator + handler in one file
      Tasks/ListTasks.cs
      Projects/InviteMember.cs
    Persistence/AppDb.cs       # pragmatic choice: slices query the DbContext directly, so it lives beside them
    Abstractions/IEmailSender.cs, IPaymentGateway.cs
  TaskBoard.Infrastructure/    # adapters to external systems: email, blob storage, payments. References Application.
    Email/SmtpEmailSender.cs
    Payments/StripePaymentGateway.cs
  TaskBoard.Api/               # composition root: Program.cs, middleware, DI wiring
tests/
  TaskBoard.ArchitectureTests/
  TaskBoard.IntegrationTests/
C#
// src/TaskBoard.Application/Features/Tasks/MoveTask.cs: one slice, everything together.
public static class MoveTask
{
    public record Request(Guid TaskId, [property: Range(0, 3)] int Status, string ETag);
    public record Response(Guid Id, int Status, string ETag);

    public static void Map(IEndpointRouteBuilder app) =>
        app.MapPatch("/api/tasks/{taskId:guid}/status", async (Guid taskId, Body body, HttpRequest req, Handler handler, CancellationToken ct) =>
            await handler.HandleAsync(new Request(taskId, body.Status, req.Headers.IfMatch.ToString()), ct))
           .RequireAuthorization();

    public record Body(int Status);

    public sealed class Handler(AppDb db, ICurrentUser user, TimeProvider clock)
    {
        public async Task<IResult> HandleAsync(Request r, CancellationToken ct)
        {
            var me = user.Id;
            var task = await db.Tasks
                .Where(t => t.Id == r.TaskId && t.Project.Members.Any(m => m.UserId == me && m.Role >= ProjectRole.Editor))
                .FirstOrDefaultAsync(ct);
            if (task is null) return Results.NotFound();

            var result = task.MoveTo((TaskState)r.Status, clock.GetUtcNow());     // rules live in the domain
            if (result.IsFailure) return Results.Problem(result.Error, statusCode: 409);

            await db.SaveChangesAsync(ct);
            return Results.Ok(new Response(task.Id, (int)task.State, ETagOf(task)));
        }
    }
}
C#
// tests/TaskBoard.ArchitectureTests: the dependency rule as an executable test (NetArchTest.Rules package).
public class DependencyRuleTests
{
    [Fact]
    public void Domain_does_not_depend_on_other_layers()
    {
        var result = Types.InAssembly(typeof(TaskItem).Assembly)
            .ShouldNot().HaveDependencyOnAny("TaskBoard.Application", "TaskBoard.Infrastructure",
                                            "Microsoft.EntityFrameworkCore", "Microsoft.AspNetCore")
            .GetResult();
        Assert.True(result.IsSuccessful, string.Join(", ", result.FailingTypeNames ?? []));
    }

    [Fact]
    public void Application_does_not_depend_on_infrastructure()
    {
        var result = Types.InAssembly(typeof(MoveTask).Assembly)
            .ShouldNot().HaveDependencyOn("TaskBoard.Infrastructure").GetResult();
        Assert.True(result.IsSuccessful);
    }

    [Fact]
    public void Every_endpoint_group_requires_authorization_or_declares_anonymous() { /* scan endpoint metadata: see Day 63 */ }
}

The pragmatic compromise in the slice is visible: it uses the DbContext directly instead of a repository interface, because for a query with an authorization filter, an abstraction would only hide the filter. The domain method MoveTo carries the rule about legal transitions, which is the part worth protecting from infrastructure concerns.

Layered code is organized by technical role, clean architecture points dependencies inward toward the domain, and vertical slices keep each feature together. A pragmatic mix, enforced by architecture tests, suits most products.
Layered code is organized by technical role, clean architecture points dependencies inward toward the domain, and vertical slices keep each feature together. A pragmatic mix, enforced by architecture tests, suits most products.

Real-World Examples

  • Alistair Cockburn described the hexagonal architecture in 2005 to keep application logic independent of user interface and database technology, and Robert C. Martin's Clean Architecture, presented in a 2012 essay and a 2017 book, generalized the dependency rule. Both are responses to systems where business rules could not be tested or evolved without dragging the entire technology stack along.
  • Jimmy Bogard, the author of AutoMapper and MediatR, has described vertical slice architecture in talks since 2018 as a reaction to layered projects where every feature crosses every layer. He advocates minimizing coupling between slices and maximizing coupling within a slice, and the approach is widely adopted in .NET teams shipping frequently.
Key TakeawaysLayered, clean and vertical slice architectures organize the same backend code in different ways, each with its own trade-offs. Layers group code by technical role, clean architecture points dependencies inward toward a domain that knows nothing of infrastructure, and vertical slices keep each feature's code together. Combine them pragmatically, avoid both architecture theater and the ball of mud, and enforce the dependency rules with architecture tests so boundaries hold as the team grows.

Review Questions & Answers

Source code dependencies may only point inward, toward the domain, so the core defines interfaces and the infrastructure implements them. That lets business rules be tested without databases or frameworks, and lets you replace or change infrastructure technologies without touching the rules. It also keeps framework details from leaking into the domain.

In a layered design one feature is spread across several folders and layers, so changing or understanding it means touching many files. A slice keeps the endpoint, validation, logic, and data access of one feature together, so change is local and each feature can use the level of sophistication it needs.

Agreements erode under deadline pressure: someone adds a using statement for expedience and the boundary disappears without anyone noticing. An automated test fails the build immediately when a forbidden dependency appears, making the rule enforceable and visible instead of relying on memory and code review.

The query embeds an authorization filter that is part of the feature's behavior, and hiding it behind a generic repository would separate the rule from where it matters. Direct use keeps the slice simple and testable through integration tests. Abstractions are added where they earn their keep, such as clocks or email, and not everywhere by default.