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

📚 Interview question

Explain Clean Architecture. What goes in the Domain, Application, Infrastructure and Presentation layers, what is the dependency rule, and what does a typical .NET 10 solution layout look like?

Explains Clean Architecture's four layers, the dependency rule and dependency inversion that make the domain independent of infrastructure, and a typical .NET 10 solution layout with its trade-offs.

Intermediate Theory Intermediate architecture aspnet-core clean-architecture dependency-inversion ef-core solution-structure

🎯 Key points

  • Dependency rule: source code dependencies point inwards, towards the domain
  • Domain: entities, value objects, domain events, rules — no references to EF Core or ASP.NET Core
  • Application: use cases (commands, queries, handlers) and the abstractions (ports) they need, such as IOrderRepository
  • Infrastructure: implements those abstractions — EF Core DbContext, repositories, email, Service Bus, file storage
  • Presentation (Web/API): HTTP endpoints and the composition root, the single place that binds abstractions to implementations
  • Dependency inversion: high-level policy and low-level detail both depend on an abstraction owned by the high-level side
  • Benefit: fast use-case tests without a database, swappable infrastructure; cost: more projects, interfaces and mapping
  • Overkill for CRUD (vertical slice or simple layering fits better); a template is not an architecture

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Clean Architecture is about one rule: source code dependencies point inwards, towards the business rules. In the middle is the Domain — entities like Order, value objects like Money, domain events and invariants — and it references nothing technical. Around it is Application, which holds the use cases: a PlaceOrder command and its handler, and the interfaces that use case needs from the outside world, like IOrderRepository or IPaymentGateway. Outside that is Infrastructure, which implements those interfaces with EF Core, Azure Service Bus, Blob Storage and so on, and Presentation — the ASP.NET Core API — which translates HTTP into use-case calls and contains the composition root in Program.cs.

The trick that makes it work is dependency inversion. In classic layering, business logic references data access. Here the Application project owns the interface and Infrastructure references Application to implement it. So the arrow from business to database is reversed: the database is a plug-in to the rules. In a .NET solution that's four projects — Domain, Application, Infrastructure, Api — with Domain having no project references at all, and an architecture test that fails the build if Domain ever references Microsoft.EntityFrameworkCore.

The mistake I see is cargo-culting the template: an anaemic domain, a repository interface per table, and a DTO mapped four times for a CRUD screen. Clean Architecture pays off when the domain has real rules and a long life; for a simple admin app it's ceremony. I'd say: invert the dependencies that protect your important rules, and don't add a layer that has nothing to protect."


The four layers

Layer Contains References Must not contain
Domain Entities, value objects, domain events, domain services, domain errors Nothing (maybe a small shared kernel) EF Core, HTTP, logging frameworks
Application Commands, queries, handlers, validators, ports (interfaces), DTOs Domain DbContext implementations, HttpContext
Infrastructure DbContext, EF configurations, migrations, repositories, email, messaging, Key Vault clients Application, Domain Business rules
Presentation Endpoints/controllers, auth setup, ProblemDetails, composition root Application (Infrastructure only for DI registration) Business rules, SQL

Classic layering vs Clean

Classic layered Clean
Business depends on Data access Nothing technical
Who owns the repository interface Data layer Application (or Domain)
Test rules without SQL Hard Easy: fake the port
Projects 3 4+

Decision table

Factor Clean fits Clean is overkill
Domain complexity Real invariants and workflows Forms over tables
Lifetime Years, many changes Short-lived or throwaway
Team size 3+ developers working in parallel One developer
Infrastructure churn Likely to swap or add providers One database, forever

Production example

In an insurance quoting service, pricing rules lived in the Domain project with no infrastructure references. The team ran 1,400 rule tests in under 4 seconds with no database, and when the rating data moved from SQL Server to a vendor API, only one Infrastructure class and its DI registration changed — the Domain and Application projects were untouched.

🔍 What the interviewer is checking

Checks that the candidate understands the dependency rule and dependency inversion behind Clean Architecture, not just the folder names, and knows when it is overkill.

Green flags

  • States that dependencies point inwards and explains how interfaces owned by Application invert the arrow
  • Puts the composition root in the Presentation layer
  • Keeps EF Core out of the Domain and mentions IEntityTypeConfiguration<T>
  • Names the costs and says when not to use it

Red flags

  • Describes it only as "four projects"
  • Has Domain or Application referencing Infrastructure
  • Believes every class needs an interface
  • Cannot say when Clean Architecture is the wrong choice

📚 Learn in depth

1. The picture

+--------------------------------------------------+
| Presentation (Api)        Infrastructure          |
|  endpoints, Program.cs     EF Core, Service Bus,  |
|                            Blob, email            |
|   +------------------------------------------+   |
|   | Application                              |   |
|   |  commands, queries, handlers, ports      |   |
|   |   +----------------------------------+   |   |
|   |   | Domain                           |   |   |
|   |   |  entities, value objects, events |   |   |
|   |   +----------------------------------+   |   |
|   +------------------------------------------+   |
+--------------------------------------------------+
         all arrows point inwards  -->  centre

2. Dependency inversion, concretely

Classic: Business → Data. Clean: the Application project declares

Application:     interface IOrderRepository { ... }   <-- owned here
Infrastructure:  class EfOrderRepository : IOrderRepository   (references Application)

At compile time Infrastructure depends on Application. At run time, Application calls Infrastructure through the interface. The flow of control goes outwards, the source dependency goes inwards. The composition root (Program.cs) is the only place that knows both.

3. The .NET project graph

Shop.Api ----------> Shop.Application ----> Shop.Domain
   |                       ^
   +-----> Shop.Infrastructure (references Application, Domain)
  • Shop.Domain.csproj: no project or framework references beyond the base library.
  • Shop.Application.csproj: references Domain; may use Microsoft.Extensions.DependencyInjection.Abstractions and FluentValidation.
  • Shop.Infrastructure.csproj: references Application; packages for EF Core, Azure SDKs.
  • Shop.Api.csproj: references Application and Infrastructure (the latter only so Program.cs can call AddInfrastructure()).

4. Where does EF Core go?

Two honest schools:

  1. Pure: Application defines repository interfaces; DbContext lives only in Infrastructure.
  2. Pragmatic: Application defines IAppDbContext exposing DbSet<T>, accepting a dependency on EF Core abstractions in exchange for using LINQ in handlers.

Both are defensible; the pragmatic one is common in .NET templates. What matters is that the Domain never references EF Core, and mapping is done with IEntityTypeConfiguration<T> in Infrastructure rather than attributes on entities.

5. Costs

  • More projects and longer build graphs.
  • Interfaces with one implementation (worth it only at real boundaries: database, messaging, external APIs, clock).
  • Mapping between entities and DTOs.
  • Features still cut across four projects — the motivation for Vertical Slice.

6. A template is not an architecture

Templates (for example, the widely used Clean Architecture templates for .NET) give you the folders. They don't give you a rich domain, sensible aggregate boundaries or a reason for each interface. Teams that only adopt the folders get the costs without the benefits.

Try it yourself

  1. Create the four projects with dotnet new classlib/webapi and wire references as above; confirm Domain builds with no references.
  2. Add an architecture test that fails if Shop.Domain references Microsoft.EntityFrameworkCore.
  3. Write a handler test with a fake IOrderRepository and time the suite.
  4. Swap the EF Core repository for an in-memory one in Program.cs and confirm no other project changes.
  5. Count the interfaces in your solution with exactly one implementation and ask which protect a real boundary.

💻 Code

The key pieces of a Clean Architecture slice: a rich entity, a port owned by Application, an Infrastructure adapter, and the composition root.

// Shop.Domain/Orders/Order.cs — no framework references
namespace Shop.Domain.Orders;

public sealed class Order
{
    private readonly List<OrderLine> _lines = [];

    private Order() { } // for EF Core materialisation

    public Guid Id { get; private set; } = Guid.NewGuid();
    public OrderStatus Status { get; private set; } = OrderStatus.Draft;
    public IReadOnlyList<OrderLine> Lines => _lines;

    public static Order Create() => new();

    public void AddLine(string sku, int quantity, decimal unitPrice)
    {
        if (Status != OrderStatus.Draft)
            throw new InvalidOperationException("Only draft orders can change."); // invariant lives in the domain
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(quantity);
        _lines.Add(new OrderLine(sku, quantity, unitPrice));
    }
}

public sealed record OrderLine(string Sku, int Quantity, decimal UnitPrice);
public enum OrderStatus { Draft, Placed, Cancelled }
// Shop.Application/Orders/AddOrderLine.cs — the use case and the port it needs
namespace Shop.Application.Orders;

using Shop.Domain.Orders;

public interface IOrderRepository // port: owned by Application, implemented by Infrastructure
{
    Task<Order?> GetAsync(Guid id, CancellationToken ct);
    Task SaveChangesAsync(CancellationToken ct);
}

public sealed record AddOrderLineCommand(Guid OrderId, string Sku, int Quantity, decimal UnitPrice);

public sealed class AddOrderLineHandler(IOrderRepository orders)
{
    public async Task<bool> HandleAsync(AddOrderLineCommand cmd, CancellationToken ct)
    {
        var order = await orders.GetAsync(cmd.OrderId, ct);
        if (order is null) return false;
        order.AddLine(cmd.Sku, cmd.Quantity, cmd.UnitPrice);
        await orders.SaveChangesAsync(ct);
        return true;
    }
}
// Shop.Infrastructure/Persistence/EfOrderRepository.cs — adapter (references Application)
namespace Shop.Infrastructure.Persistence;

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Shop.Application.Orders;
using Shop.Domain.Orders;

internal sealed class EfOrderRepository(ShopDbContext db) : IOrderRepository
{
    public Task<Order?> GetAsync(Guid id, CancellationToken ct) =>
        db.Orders.Include(o => o.Lines).SingleOrDefaultAsync(o => o.Id == id, ct);

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

public static class InfrastructureRegistration
{
    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration config)
    {
        services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(config.GetConnectionString("Shop")));
        services.AddScoped<IOrderRepository, EfOrderRepository>();
        return services;
    }
}
// Shop.Api/Program.cs — composition root
using Shop.Application.Orders;
using Shop.Infrastructure.Persistence;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddScoped<AddOrderLineHandler>();

var app = builder.Build();
app.MapPost("/orders/{id:guid}/lines", async (Guid id, AddOrderLineCommand body, AddOrderLineHandler handler, CancellationToken ct) =>
    await handler.HandleAsync(body with { OrderId = id }, ct) ? Results.NoContent() : Results.NotFound());
app.Run();

⚠ Common mistakes

  • Mistake: Domain entities with only public setters and all logic in Application handlers. Why it is wrong: the Domain layer protects nothing, so the architecture has the cost but not the benefit. Instead: put invariants and behaviour on the entities and aggregates.
  • Mistake: Application referencing Infrastructure "just for the DbContext". Why it is wrong: it breaks the dependency rule and couples use cases to EF Core's concrete types. Instead: depend on a port, or consciously choose the IAppDbContext compromise and document it.
  • Mistake: An interface for every class. Why it is wrong: one-implementation interfaces inside a layer add indirection without a boundary. Instead: create interfaces at real boundaries (database, messaging, external APIs, clock, file storage).
  • Mistake: Putting EF Core attributes or virtual navigation properties on domain entities. Why it is wrong: persistence concerns leak into the core. Instead: configure mapping with IEntityTypeConfiguration<T> in Infrastructure.
  • Mistake: Mapping the same data through four DTO types for a CRUD screen. Why it is wrong: it multiplies code without adding rules. Instead: project straight from the query to the response DTO for reads.
  • Mistake: Adopting a template and calling it done. Why it is wrong: folders don't create a domain model or sensible boundaries. Instead: decide what each layer protects and enforce it with architecture tests.
  • Mistake: Using Clean Architecture for a small internal CRUD tool. Why it is wrong: the ceremony slows delivery for no testability or flexibility gain. Instead: use a simple layered or vertical-slice design.

🏛 Senior insight: trade-offs

The value of Clean Architecture is not the four folders; it is that the code you most need to get right has no dependency on the code most likely to change. That's worth a lot in a complex, long-lived domain and almost nothing in a CRUD app. I invert dependencies at the real boundaries — persistence, messaging, external APIs, time — and resist interfaces everywhere else. I also accept pragmatic compromises (an IAppDbContext in Application) when the team agrees and records them in an ADR.

Two details separate a senior answer. First, the composition root (Program.cs plus each project's AddXxx() extension) is the only place that knows both an abstraction and its implementation; nothing else resolves from the container, which is what keeps the layers decoupled at run time as well as compile time. Second, infrastructure churn should stop at the port: when a provider changes (SQL Server to a vendor API, SMTP to Azure Communication Services) you change an adapter and a registration; if the change forces domain edits, the port was shaped around the old technology and needs redesigning in domain terms.

Option When it fits Cost When not to
Full Clean (pure ports) Complex domain, likely infrastructure change, large team Most interfaces and mapping CRUD-heavy apps
Pragmatic Clean (IAppDbContext) Rich domain, EF Core is a settled choice Application tied to EF Core abstractions When you must swap persistence
Vertical slice Many independent features, simple rules each Less shared structure Rules shared across many features

Measure the payoff: how fast the domain tests run without a database, and how many projects change for a typical feature.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says Application defines repository interfaces over EF Core. Why: Checks whether they can argue for or against wrapping DbContext in repositories.
    How to answer

    I decide by what the abstraction protects, not by habit. DbContext is already a repository and unit of work, so a wrapper has to earn its place.

    • Testability alone isn't a reason. Mocking repositories tests the mocks, and the EF in-memory provider ignores SQL semantics. I test persistence against SQL Server in Testcontainers either way.
    • Write side: repositories per aggregate root pay off when aggregates have invariants and must be loaded whole.
    • Read side: project straight from DbContext with Select and AsNoTracking. Never return IQueryable from a repository.
    • EF Core 10 ExecuteUpdateAsync/ExecuteDeleteAsync bypass the change tracker and run at once, so they belong behind an intention-revealing method and need an explicit transaction to be atomic with SaveChanges.

    My answer flips for pure CRUD (skip repositories) or for Dapper, stored procedures or a second store (repositories hide them). The trade-off is domain protection against a layer that only renames EF Core.

  2. When: Candidate mentions Program.cs wiring Infrastructure to Application interfaces. Why: Checks whether they know what the composition root is and why only it should resolve services.
    How to answer

    The composition root is the single place where the application's object graph is wired up: in ASP.NET Core, Program.cs and the AddXxx() extension methods it calls. It is the only code that knows about concrete implementations and the container.

    Everything else asks for what it needs through its constructor. If business classes call IServiceProvider.GetService themselves, that is the service locator anti-pattern: their dependencies are hidden from the signature, a missing registration only shows up at run time, and unit tests need a container instead of a couple of fakes. Keeping resolution in the root keeps business code independent of the container, easier to test and easier to maintain. Framework-driven resolution (middleware Invoke parameters, [FromServices], Minimal API parameters) is fine because it is infrastructure acting on your behalf.

  3. When: Candidate creates an interface for every service. 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

Domain project quietly picks up an EF Core dependency
Situation
A [policy administration] service built with Clean Architecture, [6] developers, deployed to Azure Australia East. Over [eight months] the domain tests slowed and a planned move of read models to Cosmos DB looked far bigger than expected.
Signals
Domain test run grew from [5 s] to [3 min] because tests needed a database; `Shop.Domain.csproj` had a `PackageReference` to `Microsoft.EntityFrameworkCore`; entities carried `[Table]` attributes and `virtual` navigation properties; the Cosmos spike estimate touched [40+] files in Domain and Application.
Investigation
Ran a dependency graph (Visual Studio Code Map / `dotnet list reference`) and found Domain → EF Core and Application → Infrastructure references. `git log` on the csproj showed the reference was added to use `[Owned]` for a value object. Searched for `DbContext` usages in Application handlers.
Resolution
Immediately: moved mapping attributes into `IEntityTypeConfiguration<T>` classes in Infrastructure and removed the EF Core package from Domain. Then: introduced ports for the two handlers that used `DbContext` directly and moved the read-model queries behind an `IOrderReadModel` interface.
Prevention
Added ArchUnitNET tests that fail the build if Domain references `Microsoft.EntityFrameworkCore` or Application references Infrastructure; wrote an ADR describing the allowed references; added the check to the PR template.

How to tell it (STAR)

**S:** On [the policy service] our domain tests had crept from [5 seconds] to [3 minutes], and a Cosmos DB spike looked huge. **T:** I was asked to work out why the architecture wasn't protecting us. **A:** I graphed the project references and found the Domain project had picked up EF Core to use one attribute, and two handlers used `DbContext` directly. I moved all mapping to `IEntityTypeConfiguration` classes, put the handlers behind ports, and added architecture tests plus an ADR so the rule was enforced, not remembered. **R:** Domain tests went back to [6 seconds], and the Cosmos read-model change touched [4] Infrastructure files instead of [40+].

↩ Usually asked after

More in Application Architectures

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me