Compares Onion, Hexagonal and Clean Architecture, explains their shared dependency-inversion core and different emphases, and shows driving and driven ports and adapters in a .NET 10 service.
They are variations of one idea: put the domain at the centre and make every source dependency point inwards, so technology plugs into the business logic rather than the reverse.
The trade-off is the same for all three: testable, swappable boundaries in exchange for more interfaces and indirection.
"They're the same core idea with different emphasis. All three put the domain in the middle and insist that source code dependencies point inwards, using dependency inversion so infrastructure depends on the application rather than the other way round. Hexagonal came first, from Alistair Cockburn in 2005, and its vocabulary is the most useful in practice: the application exposes ports — interfaces named in its own language — and adapters connect real technology to them. Onion, from Jeffrey Palermo, draws the same thing as rings. Clean, from Robert C. Martin, is a synthesis that adds the explicit dependency rule and a use-case layer.
In a .NET service I think in two directions. Driving adapters call into the app: a Minimal API endpoint, an Azure Service Bus consumer, a
BackgroundService, or a test. They invoke a use case likePlaceOrderHandler. Driven adapters are what the app calls out to:IOrderRepositoryimplemented with EF Core,IPaymentGatewayimplemented with a Stripe client,IClockimplemented withTimeProvider. The port belongs to the application and speaks business language —ChargeAsync(Money amount)— notCreatePaymentIntentAsyncwith Stripe's DTOs. For example, in a [payments] service I worked on, we [swapped the payment provider] by writing one new adapter; the handlers and their [~300] tests didn't change.The mistake I see is arguing about which name is correct, or designing ports around a vendor's API so the 'abstraction' leaks the vendor anyway. The names matter far less than two habits: ports in domain language, and dependencies pointing inwards."
| Hexagonal | Onion | Clean | |
|---|---|---|---|
| Author, year | Alistair Cockburn, 2005 | Jeffrey Palermo, 2008 | Robert C. Martin, 2012 |
| Picture | Hexagon with ports on its edges | Concentric rings | Concentric circles |
| Emphasis | Symmetry: UI and DB are both just adapters | Domain model at the core, layering inside the app | Dependency rule, use cases (interactors) |
| Key vocabulary | Port, adapter, driving, driven | Domain model, domain services, application services | Entities, use cases, interface adapters, frameworks |
| Driving (primary) | Driven (secondary) | |
|---|---|---|
| Direction | Outside world calls the app | App calls the outside world |
| Port | The use-case API (PlaceOrderHandler, a command) |
An interface the app owns (IOrderRepository) |
| .NET adapters | Minimal API endpoints, controllers, Service Bus processors, gRPC services, tests | EF Core repositories, HttpClient wrappers, Blob Storage, SMTP / Azure Communication Services |
| Factor | Ports and adapters worth it | Not worth it |
|---|---|---|
| Number of integrations | Several external systems, likely to change | One database, nothing else |
| Domain complexity | Real rules to protect | CRUD |
| Testing need | Fast tests of use cases without infrastructure | Integration tests already cover it cheaply |
| Team familiarity | Team knows the vocabulary | Would add confusion |
A logistics service had three driven adapters for carriers behind one ICarrierQuotes port. When a fourth carrier was added, the change was one adapter class (about 180 lines) and one DI registration; the domain and its 600 tests were untouched, and the release went out in two days instead of the two weeks the previous carrier integration took.
Checks that the candidate sees the shared dependency-inversion idea behind the three styles and can apply ports and adapters concretely in .NET.
Green flags
TimeProvider as a built-in port for timeRed flags
driving side driven side
[HTTP endpoint] --\ /--> [EF Core repo] -> SQL Server
[Service Bus ] ---> ( port ) [ APP ] ( port ) --> [Stripe adapter] -> Stripe
[Unit test ] --/ use cases \--> [TimeProvider]
domain inside
The hexagon shape has no meaning beyond "many sides": there's no top or bottom, so the UI isn't special. That symmetry is Cockburn's key insight — the database is just another adapter, like the UI.
+-------------------------------------------+
| UI | Infrastructure | Tests |
| +-------------------------------------+ |
| | Application services | |
| | +-------------------------------+ | |
| | | Domain services | | |
| | | +-------------------------+ | | |
| | | | Domain model | | | |
| | | +-------------------------+ | | |
| | +-------------------------------+ | |
| +-------------------------------------+ |
+-------------------------------------------+
Onion adds explicit structure inside the application (domain model vs domain services vs application services) that Hexagonal leaves open.
IPaymentGateway.ChargeAsync(CustomerId, Money), not IStripeService.CreatePaymentIntentAsync(PaymentIntentCreateOptions).A port shaped like the vendor API is a leaky port: replacing the vendor still means changing the application.
Application; adapters in Infrastructure; registered in the composition root (services.AddScoped<IPaymentGateway, StripePaymentGateway>()).HttpClient adapters with AddHttpClient<TClient>() and AddStandardResilienceHandler() keep resilience inside the adapter.TimeProvider is a built-in driven port; FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) is its test adapter.Because tests are "just another driving adapter", you can run use cases end to end in memory with fake driven adapters, then run a smaller set of integration tests (Testcontainers for SQL Server) per real adapter. Each adapter gets contract tests that both the fake and the real one must pass.
IClock-free handler that uses TimeProvider, and test an expiry rule with FakeTimeProvider.Advance.IPaymentGateway in domain terms; write a fake and a real adapter; write one contract test both must pass.A driven port in domain language, two adapters (real and fake), and a driving adapter (an endpoint).
// Application: the port and the use case
namespace Payments.Application;
public readonly record struct Money(decimal Amount, string Currency);
public sealed record ChargeResult(bool Succeeded, string? Reference, string? FailureReason);
public interface IPaymentGateway // driven port, owned by the application
{
Task<ChargeResult> ChargeAsync(Guid customerId, Money amount, string idempotencyKey, CancellationToken ct);
}
public sealed record TakePayment(Guid OrderId, Guid CustomerId, Money Amount);
public sealed class TakePaymentHandler(IPaymentGateway gateway, TimeProvider clock)
{
public async Task<ChargeResult> HandleAsync(TakePayment cmd, CancellationToken ct)
{
// The order id doubles as the idempotency key, so a retried request can't charge twice.
var result = await gateway.ChargeAsync(cmd.CustomerId, cmd.Amount, cmd.OrderId.ToString(), ct);
_ = clock.GetUtcNow(); // e.g. stamp the payment time via a testable port
return result;
}
}
// Infrastructure: a real driven adapter and a fake one for tests
namespace Payments.Infrastructure;
using System.Net.Http.Json;
using Payments.Application;
internal sealed class HttpPaymentGateway(HttpClient http) : IPaymentGateway
{
private sealed record ProviderRequest(Guid Customer, long AmountInCents, string Currency);
private sealed record ProviderResponse(string Id, string Status, string? Error);
public async Task<ChargeResult> ChargeAsync(Guid customerId, Money amount, string idempotencyKey, CancellationToken ct)
{
using var request = new HttpRequestMessage(HttpMethod.Post, "charges")
{
Content = JsonContent.Create(new ProviderRequest(customerId, (long)(amount.Amount * 100), amount.Currency))
};
request.Headers.Add("Idempotency-Key", idempotencyKey);
using var response = await http.SendAsync(request, ct);
var body = await response.Content.ReadFromJsonAsync<ProviderResponse>(ct);
// Translate the provider's shape into the port's result: vendor details stay in the adapter.
return body is { Status: "succeeded" }
? new ChargeResult(true, body.Id, null)
: new ChargeResult(false, null, body?.Error ?? $"HTTP {(int)response.StatusCode}");
}
}
public sealed class FakePaymentGateway : IPaymentGateway
{
public List<(Guid Customer, Money Amount)> Charges { get; } = [];
public Task<ChargeResult> ChargeAsync(Guid customerId, Money amount, string idempotencyKey, CancellationToken ct)
{
Charges.Add((customerId, amount));
return Task.FromResult(new ChargeResult(true, $"fake-{Charges.Count}", null));
}
}
// Api/Program.cs: the composition root and a driving adapter
using Payments.Application;
using Payments.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddHttpClient<IPaymentGateway, HttpPaymentGateway>(c =>
c.BaseAddress = new Uri(builder.Configuration["Payments:BaseUrl"]!))
.AddStandardResilienceHandler(); // resilience belongs to the adapter, not the domain
builder.Services.AddScoped<TakePaymentHandler>();
var app = builder.Build();
app.MapPost("/payments", async (TakePayment cmd, TakePaymentHandler handler, CancellationToken ct) =>
await handler.HandleAsync(cmd, ct) is { Succeeded: true } r
? Results.Ok(r)
: Results.Problem(statusCode: StatusCodes.Status402PaymentRequired));
app.Run();
AddStandardResilienceHandler comes from the Microsoft.Extensions.Http.Resilience package.
IStripeService). Why it is wrong: changing vendor still changes the application, so the port protects nothing. Instead: name ports and their types in domain language.StripeException or SqlException. Instead: translate to domain results or errors inside the adapter.HttpClient with Microsoft.Extensions.Http.Resilience.I use the hexagonal vocabulary because it is the most precise: "driving" and "driven" make it obvious that HTTP, queues and tests are equals, and "port in domain language" is a design rule you can review. Whether the folders are called Onion or Clean matters far less than whether the ports are shaped by the domain. The real skill is choosing where to put ports: every external system and anything non-deterministic (time, randomness, IDs), but not between two classes inside the same module.
In .NET the wiring is all in the composition root. One adapter per port is a plain AddScoped<IPort, Adapter>(); several live adapters (one per carrier or per region) use keyed services (AddKeyedScoped<ICarrierQuotes, AusPostQuotes>("auspost") with [FromKeyedServices]) or a small strategy that picks by tenant or market. Ports should evolve additively — add a method or a new port rather than changing a signature every adapter implements — and every adapter of a port passes the same contract tests, which is what makes adding the next integration cheap. The run-time cost of the indirection (an interface call, a DI lookup) is negligible next to the I/O the adapter performs; the real cost is cognitive, so keep the number of ports small.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Full ports and adapters | Several integrations, complex domain, need fast in-memory tests | Interfaces, fakes and contract tests per port | Single-database CRUD |
| Ports only for external systems | Most business services | Light | When even those never change and integration tests are cheap |
| No ports (direct SDK use) | Scripts, prototypes, tiny services | Vendor lock-in, slower tests | Anything long-lived with real rules |
Measure it by the blast radius of a provider change (files touched) and the run time of the use-case test suite without infrastructure.
Clean Architecture (Robert C. Martin, 2012) arranges code in concentric layers with one rule: source code dependencies point inwards.
IOrderRepository or IEmailSender.The key move is dependency inversion: the database depends on the domain, not the other way round. The trade-off: testable, technology-independent rules in exchange for more projects, interfaces and mapping — overkill for simple CRUD.
I do not abstract when there is no second variant, no boundary to protect and no testing need, because an abstraction costs indirection, a name, a contract and cognitive load. Typical examples are an IOrderService with one implementation used by one controller, a generic repository over EF Core, or a wrapper around HttpClient or ILogger<T>, which are already abstractions. I do abstract at architecture boundaries (ports for payment vendors, email, storage) and where tests need a seam for something slow or non-deterministic. If an abstraction has had one implementation and one caller for a long time and is not at a boundary, I inline it.
How to tell it (STAR)
**S:** At [company] we had to move [40k monthly charges] to a cheaper payment provider within [a quarter], but the first estimate touched [70+] files. **T:** I was asked to make the switch safe and fast. **A:** I found our 'port' was really the old vendor's API with an interface on it. I proposed, in an ADR, a domain-shaped `IPaymentGateway`, wrapped the old provider in an adapter first, migrated handlers behind it, then added the new adapter behind a per-merchant feature flag with shared contract tests. **R:** We switched [100%] of traffic in [five weeks] with [zero] double charges, and the next provider change would touch one adapter.
Last updated 23 Nov 2026.