H Hexagonal Architecture
/
01Overview
02Core Tenets
03Solution Structure
04Worked Example
05Runtime Flows
06Change-Impact Analysis
07Testing Strategy
08When To Use It
09Pros and Cons
10Comparison
11Reference Checklist
Architecture Reference · C# / .NET 10

Ports in, adapters out.
Nothing touches the core.

Alistair Cockburn's Ports & Adapters, in full — the two-sided symmetry, every port and adapter, dependency inversion made concrete, runtime flows, and exactly what breaks when a port changes shape.

11 sections 8 live diagrams 9 code samples ~18 min read
CORE ports inside REST CLI DB BUS DRIVING ADAPTERS DRIVEN ADAPTERS
Scroll to begin
01

Overview

Hexagonal Architecture — Alistair Cockburn's Ports and Adapters, 2005 — makes one structural claim: the application core should be reachable and drivable without knowing what is on the other side of the wire. Everything external plugs into it through explicit, core-owned interfaces called ports. The code that does the plugging is an adapter.

Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases.

The hexagon shape carries no meaning about six sides. Cockburn chose it to give room to draw multiple distinct ports around a boundary, and to break the habit of thinking in top-down layers.

DIAGRAM 01
flowchart LR subgraph DRIVING["Driving side — primary adapters"] UI["Web UI"] API["REST Controller"] CLI["CLI"] TEST["Test harness"] end subgraph CORE["Application core"] PIN["Driving ports<br/>use case interfaces"] APP["Application services<br/>Domain model"] POUT["Driven ports<br/>SPI interfaces"] end subgraph DRIVEN["Driven side — secondary adapters"] DB["EF Core repository"] SMTP["SMTP sender"] BUS["Message bus"] end UI --> PIN API --> PIN CLI --> PIN TEST --> PIN PIN --> APP APP --> POUT POUT -.->|implemented by| DB POUT -.->|implemented by| SMTP POUT -.->|implemented by| BUS
02

Core Tenets

Four rules define membership. An architecture satisfying all four is Ports and Adapters, whatever the folders are called:

  • The core owns its interfaces. Ports are declared inside the core, in the core's vocabulary — never imported from an adapter or a framework.
  • Symmetry of the two sides. A driving adapter (UI, CLI, test) and a driven adapter (database, bus) are architecturally the same kind of thing: interchangeable edges.
  • The core is runnable in isolation. It must compile and execute with every real adapter replaced by a fake. This is the falsifiable test.
  • Adapters depend inward, never the reverse. No core type may name an adapter type.

Note what is not a tenet: a specific number of ports, a specific project layout, or a DI container. Those are conveniences.

DIAGRAM 02
flowchart RL ADAPTER["SqlBookingRepository<br/><i>Driven adapter</i>"] -.->|implements| PORT["IBookingRepository<br/><i>Driven port — owned by core</i>"] SERVICE["BookAppointment<br/><i>Application core</i>"] -->|depends on abstraction| PORT ADAPTER --> DB[("PostgreSQL")] ROOT["Composition root"] -->|binds at startup| ADAPTER

The interface is defined by the consumer. IBookingRepository exposes the methods the use case needs, not the ones the database finds convenient.

C#
// Core/Application/Ports/Driven/IBookingRepository.cs
namespace Clinic.Core.Application.Ports.Driven;

/// <summary>Driven port. Declared BY the core, implemented outside it.</summary>
public interface IBookingRepository
{
    Task<IReadOnlyList<Appointment>> FindConflictingAsync(
        TimeSlot slot, CancellationToken ct = default);

    void Add(Appointment appointment);
    Task CommitAsync(CancellationToken ct = default);
}
C#
// Core/Application/Ports/Driving/IBookAppointment.cs
namespace Clinic.Core.Application.Ports.Driving;

/// <summary>Driving port. The core's offered API — what the app can DO.</summary>
public interface IBookAppointment
{
    Task<BookingResult> HandleAsync(
        BookAppointmentCommand command, CancellationToken ct = default);
}

public sealed record BookAppointmentCommand(
    Guid PatientId, DateTimeOffset Start, TimeSpan Duration);
03

Solution Structure

The project reference matrix is the architecture — it is enforced by the compiler, not by convention.

ProjectSideReferences
Clinic.CoreCorenone
Clinic.Adapters.PersistenceDrivenClinic.Core
Clinic.Adapters.NotificationsDrivenClinic.Core
Clinic.Adapters.ApiDrivingClinic.Core + all adapters (composition only)
Clinic.Tests.CoreTestClinic.Core

The core project should be actively hostile to dependencies:

XML
<!-- Core/Clinic.Core.csproj — deliberately dependency-free -->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
  </PropertyGroup>
  <!-- No ProjectReference. No PackageReference. This is the whole point. -->
</Project>
04

Worked Example

A clinic booking system. Rules: appointments fall within working hours, cannot be booked in the past, cannot overlap an existing booking, and require 24 hours' notice to cancel. Watch where each rule lands.

The domain — rules live here

C#
// Core/Domain/Appointments/Appointment.cs
namespace Clinic.Core.Domain.Appointments;

public sealed class Appointment
{
    public AppointmentId Id { get; private set; }
    public PatientId PatientId { get; private set; }
    public TimeSlot Slot { get; private set; }
    public AppointmentStatus Status { get; private set; }

    private Appointment() { }   // ORM materialisation only

    public static Appointment Book(PatientId patient, TimeSlot slot, IClock clock)
    {
        if (!slot.FallsWithinWorkingHours())
            throw new DomainException("Appointments must fall within working hours.");
        if (slot.Start <= clock.UtcNow)
            throw new DomainException("Cannot book an appointment in the past.");

        return new Appointment
        {
            Id = AppointmentId.New(),
            PatientId = patient,
            Slot = slot,
            Status = AppointmentStatus.Booked
        };
    }

    public void Cancel(IClock clock)
    {
        if (Status is not AppointmentStatus.Booked)
            throw new DomainException($"Cannot cancel an appointment that is {Status}.");
        if (Slot.Start - clock.UtcNow < TimeSpan.FromHours(24))
            throw new DomainException("Cancellations require 24 hours' notice.");

        Status = AppointmentStatus.Cancelled;
    }
}

The use case — orchestration only, no business rules

C#
// Core/Application/UseCases/BookAppointment.cs
internal sealed class BookAppointment(
    IBookingRepository bookings,
    IClock clock,
    ILogger<BookAppointment> logger) : IBookAppointment
{
    public async Task<BookingResult> HandleAsync(
        BookAppointmentCommand command, CancellationToken ct = default)
    {
        var slot = new TimeSlot(command.Start, command.Duration);

        var conflicts = await bookings.FindConflictingAsync(slot, ct);
        if (conflicts.Count > 0)
            return BookingResult.Conflict(conflicts.Count);

        // All business rules live in the domain, not here.
        var appointment = Appointment.Book(new PatientId(command.PatientId), slot, clock);

        bookings.Add(appointment);
        await bookings.CommitAsync(ct);

        logger.LogInformation("Booked {AppointmentId}", appointment.Id);
        return BookingResult.Booked(appointment.Id.Value);
    }
}

The driven adapter — the only place the ORM appears

C#
// Adapters/Driven/Persistence/SqlBookingRepository.cs
internal sealed class SqlBookingRepository(ClinicDbContext db) : IBookingRepository
{
    public async Task<IReadOnlyList<Appointment>> FindConflictingAsync(
        TimeSlot slot, CancellationToken ct = default) =>
        await db.Appointments
            .Where(a => a.Status == AppointmentStatus.Booked
                     && a.Slot.Start < slot.End
                     && slot.Start < a.Slot.End)
            .ToListAsync(ct);

    public void Add(Appointment appointment) => db.Appointments.Add(appointment);

    public Task CommitAsync(CancellationToken ct = default) => db.SaveChangesAsync(ct);
}

The composition root — the only place concrete types are named

C#
// Adapters/Driving/Api/Program.cs — the ONLY place concrete types are named
var builder = WebApplication.CreateBuilder(args);

// Driving side
builder.Services.AddScoped<IBookAppointment, BookAppointment>();

// Driven side — ports bound to adapters
builder.Services.AddDbContext<ClinicDbContext>(o =>
    o.UseNpgsql(builder.Configuration.GetConnectionString("Clinic")));
builder.Services.AddScoped<IBookingRepository, SqlBookingRepository>();
builder.Services.AddScoped<INotificationSender, SmtpNotificationSender>();
builder.Services.AddSingleton<IClock, SystemClock>();

var app = builder.Build();
app.MapPost("/appointments", async (
    BookAppointmentCommand cmd, IBookAppointment useCase, CancellationToken ct) =>
{
    var result = await useCase.HandleAsync(cmd, ct);
    return result.IsBooked
        ? Results.Created($"/appointments/{result.Id}", result)
        : Results.Conflict(result);
});
app.Run();
05

Runtime Flows

The happy path. Note that steps 9–13 involve no I/O at all — the entire business decision is made against in-memory objects, which is why these rules test in microseconds.

DIAGRAM 03
sequenceDiagram autonumber actor Client participant API as REST adapter<br/>driving participant UC as BookAppointment<br/>driving port impl participant DOM as Appointment<br/>domain participant REPO as IBookingRepository<br/>driven port participant SQL as SqlBookingRepository<br/>driven adapter participant DB as PostgreSQL Client->>API: POST /appointments API->>UC: Handle(BookAppointmentCommand) UC->>REPO: FindConflicting(slot) REPO->>SQL: (runtime binding) SQL->>DB: SELECT ... WHERE slot overlaps DB-->>SQL: 0 rows SQL-->>UC: empty Note over UC,DOM: Business rules run in memory — no I/O UC->>DOM: Appointment.Book(patient, slot, clock) DOM->>DOM: validate slot in working hours DOM->>DOM: raise AppointmentBooked DOM-->>UC: appointment UC->>REPO: Add(appointment) UC->>REPO: Commit() REPO->>SQL: (runtime binding) SQL->>DB: INSERT + COMMIT DB-->>SQL: ok UC-->>API: BookingResult API-->>Client: 201 Created

The rejection path. Because the domain refuses to construct an invalid appointment, persistence is never reached and there is no partial write to compensate for.

DIAGRAM 04
sequenceDiagram autonumber actor Client participant API as REST adapter participant UC as BookAppointment participant DOM as Appointment participant DB as PostgreSQL Client->>API: POST /appointments (03:00 slot) API->>UC: Handle(command) UC->>DOM: Appointment.Book(patient, slot, clock) DOM->>DOM: slot outside working hours DOM--xUC: throw DomainException Note over UC,DB: Persistence never reached — no partial write UC--xAPI: exception propagates API-->>Client: 400 ProblemDetails
06

Change-Impact Analysis

Hexagonal's equivalent of "what happens when the model changes" is what happens when a port changes. Ports are the contract surface; they are also the thing every adapter and every test fake depends on.

DIAGRAM 05
flowchart TD START{"A driven port needs to change"} --> Q1{"Is the change purely<br/>ADDITIVE to the interface?"} Q1 -->|"Yes — new method"| C1["Core + every adapter<br/>implementing that port"] Q1 -->|No| Q2{"Does it change an<br/>existing signature?"} Q2 -->|Yes| C2["Core + all adapters<br/>+ all fakes in tests<br/>compiler enumerates every site"] Q2 -->|No| C3["Adapter-internal only<br/>Blast radius: one project"]
ChangeCoreDriven adaptersDriving adaptersTest fakesMigration
Add a method to a driven port●● all of them–● all of them○
Change an existing port signature●● all of them◐● all of them○
Change adapter internals only–● one––◐
Add a new driving port (use case)●–◐○–
Swap an adapter implementation–● one new––◐

The last two rows are the payoff. The second row is the cost — and it is a real one: a port with many implementations is expensive to change, which is the honest argument against defining a port for something that will only ever have one adapter.

The compiler breaking is the feature. A port change enumerates every site that must be reconsidered, at build time, instead of failing in production.

07

Testing Strategy

DIAGRAM 06
flowchart TD T4["Architecture fitness tests<br/>core must not reference adapters"] T3["Adapter integration tests<br/>Testcontainers · WireMock"] T2["Use-case tests via driving ports<br/>in-memory fakes for driven ports"] T1["Domain unit tests<br/>no mocks at all"] T1 --- T2 --- T3 --- T4

Domain tests use no test doubles at all. If a rule needs a mock to test, the rule is in the wrong place.

C#
// Tests/Core.UnitTests/AppointmentTests.cs — no mocks, no DB, no container
public class AppointmentTests
{
    private static readonly IClock Clock =
        new FixedClock(new DateTimeOffset(2026, 8, 12, 9, 0, 0, TimeSpan.Zero));

    [Fact]
    public void Book_OutsideWorkingHours_Throws()
    {
        var slot = new TimeSlot(
            new DateTimeOffset(2026, 8, 13, 3, 0, 0, TimeSpan.Zero), TimeSpan.FromMinutes(30));

        var act = () => Appointment.Book(PatientId.New(), slot, Clock);

        act.Should().Throw<DomainException>().WithMessage("*working hours*");
    }

    [Fact]
    public void Cancel_WithLessThan24HoursNotice_Throws()
    {
        var slot = new TimeSlot(Clock.UtcNow.AddHours(6), TimeSpan.FromMinutes(30));
        var appointment = Appointment.Book(PatientId.New(), slot, Clock);

        var act = () => appointment.Cancel(Clock);

        act.Should().Throw<DomainException>().WithMessage("*24 hours*");
    }
}

Use-case tests substitute driven ports with hand-written fakes. This is what "the core is runnable in isolation" buys you, made concrete:

C#
// Tests/Core.UnitTests/Fakes/InMemoryBookingRepository.cs
// A fake driven adapter. This is the payoff of ports: the core is testable
// end-to-end with zero infrastructure.
internal sealed class InMemoryBookingRepository : IBookingRepository
{
    private readonly List<Appointment> _saved = [];
    public IReadOnlyList<Appointment> Saved => _saved;

    public Task<IReadOnlyList<Appointment>> FindConflictingAsync(
        TimeSlot slot, CancellationToken ct = default) =>
        Task.FromResult<IReadOnlyList<Appointment>>(
            _saved.Where(a => a.Slot.Overlaps(slot)).ToList());

    public void Add(Appointment appointment) => _saved.Add(appointment);
    public Task CommitAsync(CancellationToken ct = default) => Task.CompletedTask;
}
08

When To Use It

DIAGRAM 07
flowchart TD S{"Should I use Hexagonal?"} --> A{"More than one way in?<br/>API + jobs + CLI + tests"} A -->|No| B{"Infrastructure likely<br/>to be swapped or stubbed?"} A -->|Yes| Y1["Strong fit"] B -->|No| N1["Probably overkill —<br/>a plain layered app is honest"] B -->|Yes| Y2["Good fit"]

Use it when

  • There is genuinely more than one way in — REST plus scheduled jobs plus a CLI plus tests.
  • Infrastructure is uncertain, plural, or slow enough that stubbing it materially speeds development.
  • The business rules are worth protecting from framework churn over a long lifetime.

Don't use it when

  • The app is CRUD with one entry point — you will write ports with exactly one implementation forever.
  • The team treats ports as a mechanical ritual rather than a boundary decision, producing one interface per class and calling it architecture.
  • The system is short-lived. The insurance never pays out.
09

Pros and Cons

BenefitWhat it actually buys you
Testable coreThe entire application is exercisable with fakes — not just units, the whole use case.
Deferred decisionsYou can build and test before choosing a database or a delivery mechanism.
Symmetric substitutionA test harness is architecturally identical to a UI. That is why it works.
Framework churn toleranceBusiness rules outlive the framework they were first written against.
CostThe reality
Port proliferationOne interface per collaborator, most with a single implementation. Speculative generality is the standard failure.
IndirectionF12 lands on an interface. Stack traces cross assemblies.
Contested value for the DB portWrapping a modern ORM in a repository port duplicates a unit-of-work that already exists, and can hide capabilities like projections and split queries.
Says nothing about the insideHexagonal specifies only inside-vs-outside. The core's own structure is left entirely to you — which is why Onion and Clean exist.
10

Comparison

DIAGRAM 08
flowchart TB subgraph HEX["Hexagonal — inside vs outside"] H1["Adapters"] --> H2["Ports"] --> H3["Core"] end subgraph ONION["Onion — concentric rings"] O1["Presentation / Infra"] --> O2["Application"] --> O3["Domain"] end subgraph LAYERED["N-Tier — top down"] L1["Presentation"] --> L2["Business"] --> L3["Data Access"] end
DimensionHexagonalOnionN-Tier
Author / yearCockburn, 2005Palermo, 2008Fowler, 2002
Primary axisInside vs outsideConcentric rings around a domainTechnical layers
Dependency directionInward, toward the coreInward, toward the domainDownward, toward the DB
Prescribed rings23–43–4
Says how to structure the core?No — deliberatelyYesPartially
Main failure modePort proliferationAnemic domainDomain shaped by schema

Onion is best read as Hexagonal with the inside subdivided. They impose the same constraint; Onion just also tells you what to do once you are inside the boundary. In .NET practice the terms are used almost interchangeably, and that is mostly harmless.

11

Reference Checklist

Use this in code review.

  • ✅ Core.csproj has zero package and project references
  • ✅ Every port is declared in the core, in the core's vocabulary
  • ✅ No port signature exposes an ORM, HTTP, or framework type
  • ✅ Driving and driven ports live in separate, clearly named folders
  • ✅ Adapters are internal and bound only at the composition root
  • ✅ The core builds and its tests pass with every real adapter absent
  • ✅ Each port has a reason to exist beyond "we might swap it someday"
  • ✅ Architecture fitness test asserts the core references no adapter namespace