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.
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.
The interface is defined by the consumer. IBookingRepository exposes the methods the use case needs, not the ones the database finds convenient.
// 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);
}// 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);Solution Structure
The project reference matrix is the architecture — it is enforced by the compiler, not by convention.
| Project | Side | References |
|---|---|---|
Clinic.Core | Core | none |
Clinic.Adapters.Persistence | Driven | Clinic.Core |
Clinic.Adapters.Notifications | Driven | Clinic.Core |
Clinic.Adapters.Api | Driving | Clinic.Core + all adapters (composition only) |
Clinic.Tests.Core | Test | Clinic.Core |
The core project should be actively hostile to dependencies:
<!-- 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>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
// 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
// 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
// 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
// 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();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.
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.
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.
| Change | Core | Driven adapters | Driving adapters | Test fakes | Migration |
|---|---|---|---|---|---|
| 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.
Testing Strategy
Domain tests use no test doubles at all. If a rule needs a mock to test, the rule is in the wrong place.
// 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:
// 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;
}When To Use It
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.
Pros and Cons
| Benefit | What it actually buys you |
|---|---|
| Testable core | The entire application is exercisable with fakes — not just units, the whole use case. |
| Deferred decisions | You can build and test before choosing a database or a delivery mechanism. |
| Symmetric substitution | A test harness is architecturally identical to a UI. That is why it works. |
| Framework churn tolerance | Business rules outlive the framework they were first written against. |
| Cost | The reality |
|---|---|
| Port proliferation | One interface per collaborator, most with a single implementation. Speculative generality is the standard failure. |
| Indirection | F12 lands on an interface. Stack traces cross assemblies. |
| Contested value for the DB port | Wrapping 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 inside | Hexagonal specifies only inside-vs-outside. The core's own structure is left entirely to you — which is why Onion and Clean exist. |
Comparison
| Dimension | Hexagonal | Onion | N-Tier |
|---|---|---|---|
| Author / year | Cockburn, 2005 | Palermo, 2008 | Fowler, 2002 |
| Primary axis | Inside vs outside | Concentric rings around a domain | Technical layers |
| Dependency direction | Inward, toward the core | Inward, toward the domain | Downward, toward the DB |
| Prescribed rings | 2 | 3–4 | 3–4 |
| Says how to structure the core? | No — deliberately | Yes | Partially |
| Main failure mode | Port proliferation | Anemic domain | Domain 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.
Reference Checklist
Use this in code review.
- ✅
Core.csprojhas 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
internaland 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