📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Onion, Hexagonal (ports and adapters) and Clean Architecture: are they the same idea or not? Explain what each emphasises, what ports and adapters look like in a .NET service, and where driving and driven adapters live.

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.

Mid-Level Theory Intermediate architecture clean-architecture dependency-inversion hexagonal-architecture onion-architecture ports-and-adapters

🎯 Key points

  • Same core idea: the domain sits in the centre and all source dependencies point inwards
  • Hexagonal (Alistair Cockburn, 2005): an application with ports; adapters plug technology into them
  • Driving (primary) adapters call the app: Minimal API endpoints, Service Bus consumers, BackgroundServices, tests; driven (secondary) adapters are called by it: EF Core, email, payment APIs
  • Port = an interface in the application's own language, e.g. IPaymentGateway, not IStripeClient; adapters translate vendor errors into domain results
  • Onion (Jeffrey Palermo, 2008): concentric rings — domain model, domain services, application services, outer infrastructure/UI/tests
  • Clean (Robert C. Martin, 2012): synthesises both, adds the explicit dependency rule and use-case (interactor) layer
  • Adapters are bound in the composition root; several adapters per port via keyed services or a strategy, fakes for tests
  • Ports evolve additively (new methods, new ports) so adapters can be added or replaced without touching the domain

⏱ 30-second answer

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.

  • Hexagonal / ports and adapters (Cockburn, 2005) frames it as an application with ports (interfaces in the app's language) and adapters: driving adapters call in (HTTP endpoints, message consumers, tests); driven adapters are called out to (SQL Server, email, payment APIs).
  • Onion (Palermo, 2008) draws concentric rings: domain model, domain services, application services, then infrastructure and UI.
  • Clean (Martin, 2012) combines them with an explicit dependency rule and a use-case layer.

The trade-off is the same for all three: testable, swappable boundaries in exchange for more interfaces and indirection.

🗣 Full answer (senior)

How I would answer this in an interview

"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 like PlaceOrderHandler. Driven adapters are what the app calls out to: IOrderRepository implemented with EF Core, IPaymentGateway implemented with a Stripe client, IClock implemented with TimeProvider. The port belongs to the application and speaks business language — ChargeAsync(Money amount) — not CreatePaymentIntentAsync with 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."


Side by side

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 vs driven

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

Decision table

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

Production example

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.

🔍 What the interviewer is checking

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

  • Says they're variations of one idea and names what each emphasises
  • Distinguishes driving and driven adapters with .NET examples
  • Insists ports use domain language and translate vendor errors
  • Knows TimeProvider as a built-in port for time

Red flags

  • Claims they are completely different architectures, or can't tell them apart at all
  • Designs ports around vendor SDK types
  • Thinks only the database is an adapter

📚 Learn in depth

1. The hexagon

           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.

2. Onion rings

+-------------------------------------------+
| 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.

3. What makes a good port

  • Named in domain language: IPaymentGateway.ChargeAsync(CustomerId, Money), not IStripeService.CreatePaymentIntentAsync(PaymentIntentCreateOptions).
  • Shaped by the use case's needs, not by the provider's capabilities.
  • Returns domain results or errors, not provider exceptions.
  • Owned by the application project, so the adapter project references the application.

A port shaped like the vendor API is a leaky port: replacing the vendor still means changing the application.

4. How .NET wires it

  • Driven ports: interfaces in Application; adapters in Infrastructure; registered in the composition root (services.AddScoped<IPaymentGateway, StripePaymentGateway>()).
  • Typed HttpClient adapters with AddHttpClient<TClient>() and AddStandardResilienceHandler() keep resilience inside the adapter.
  • Time: .NET 8+ TimeProvider is a built-in driven port; FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing) is its test adapter.
  • Driving adapters: endpoints and consumers resolve the use case from DI and translate results to HTTP or message acknowledgements.

5. Testing benefits

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.

6. Costs and limits

  • More interfaces and DI registrations.
  • Over-abstraction when a port has exactly one adapter forever and no test benefit.
  • It says nothing about how to split a large system — that's bounded contexts and modules.

Try it yourself

  1. Write an IClock-free handler that uses TimeProvider, and test an expiry rule with FakeTimeProvider.Advance.
  2. Define IPaymentGateway in domain terms; write a fake and a real adapter; write one contract test both must pass.
  3. Draw your current service as a hexagon: list every driving and driven adapter.
  4. Find a port in your codebase whose method names come from a vendor SDK and rename it in domain language.

💻 Code

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.

⚠ Common mistakes

  • Mistake: Arguing that Onion, Hexagonal and Clean are fundamentally different architectures. Why it is wrong: they share the same dependency-inversion core; the differences are emphasis and vocabulary. Instead: explain the shared idea, then the emphasis of each.
  • Mistake: Shaping ports around a vendor SDK (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.
  • Mistake: Letting provider exceptions cross the port. Why it is wrong: the application ends up catching StripeException or SqlException. Instead: translate to domain results or errors inside the adapter.
  • Mistake: Treating only the database as an adapter and the UI as special. Why it is wrong: it misses that endpoints, consumers and tests are all driving adapters, which is what makes in-memory testing possible. Instead: model both sides symmetrically.
  • Mistake: Creating ports for things that never vary and have no test benefit. Why it is wrong: extra indirection with no payoff. Instead: add ports at real boundaries: persistence, messaging, external APIs, time, files.
  • Mistake: Putting retry and circuit-breaker logic in handlers. Why it is wrong: resilience is a technical concern of the adapter. Instead: configure it on the typed HttpClient with Microsoft.Extensions.Http.Resilience.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the dependency rule or concentric layers. Why: Checks whether they can lay out a Clean Architecture solution and say what goes in each layer.
    How to answer

    Clean Architecture (Robert C. Martin, 2012) arranges code in concentric layers with one rule: source code dependencies point inwards.

    • Domain (centre): entities, value objects, domain events and business rules — no EF Core, no ASP.NET Core.
    • Application: use cases (commands, queries, handlers) plus the interfaces they need, such as IOrderRepository or IEmailSender.
    • Infrastructure: implements those interfaces with EF Core, Azure Service Bus, Blob Storage.
    • Presentation: endpoints and the composition root that wires implementations to interfaces.

    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.

  2. When: Candidate wants a port for every dependency. Why: Checks whether they can tell when an abstraction earns its keep.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Vendor-shaped port makes a payment provider switch a rewrite
Situation
A [subscription billing] service on Azure, [~40k] charges a month. The business negotiated a cheaper payment provider and asked for the switch within [one quarter].
Signals
The spike estimate touched [70+] files: handlers caught the old SDK's exception types, used its enums for payment status, and the `IPaymentService` interface exposed SDK option classes. Unit tests mocked the SDK's types directly.
Investigation
Grepped for the vendor namespace outside Infrastructure; drew the hexagon on a whiteboard listing every driven port; ran an ArchUnitNET rule 'Application must not depend on Vendor.*' which reported [112] violations.
Resolution
First, introduced a new `IPaymentGateway` port in domain terms (`ChargeAsync(CustomerId, Money, idempotencyKey)` returning `ChargeResult`) with an adapter for the old provider, and migrated handlers one at a time behind it. Then wrote the new provider's adapter, ran both behind a feature flag per merchant, and switched over gradually.
Prevention
Architecture test banning vendor namespaces outside Infrastructure; contract tests every payment adapter must pass; an ADR stating ports are named in domain language; PR checklist item.

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.

↩ Usually asked after

More in Application Architectures

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me