C# / .NET Compendium PLEN
.NET / C# / SOLID, Clean Code, DI

Clean Architecture - an architecture independent of frameworks and the database

What it is and where it comes from

Clean Architecture is a style of organising code described by Robert C. Martin ("Uncle Bob") on his blog in 2012 and expanded in a book in 2017. It is not an entirely new idea - it is a synthesis of several earlier approaches that share a common goal:

  • Hexagonal Architecture (Ports and Adapters, Alistair Cockburn, 2005),
  • Onion Architecture (Jeffrey Palermo, 2008),
  • BCE / DCI and other architectures focused on business logic.

The shared idea: business logic is the heart of the application and must not depend on technical details - the database, the web framework, the UI, external APIs. The details are supposed to depend on the logic, not the other way round.

What this gives you in practice:

  • Testability - business logic can be tested without a database, without an HTTP server, without a DI container,
  • Replaceable details - switching from EF Core to Dapper or from SQL Server to PostgreSQL touches one layer, not the whole application,
  • Deferred decisions - you can start writing logic before deciding on the database or the UI,
  • Longevity - frameworks get old (WinForms, WCF, ASP.NET MVC 5), but the business rules stay.

The Dependency Rule

This is the one truly key rule of the whole approach. The architecture is drawn as concentric circles:

┌─────────────────────────────────────────────────────────┐
│  Frameworks & Drivers   (Web, UI, DB, external APIs)    │
│  ┌───────────────────────────────────────────────────┐  │
│  │  Interface Adapters   (kontrolery, repozytoria)   │  │
│  │  ┌─────────────────────────────────────────────┐  │  │
│  │  │  Use Cases   (logika aplikacji)             │  │  │
│  │  │  ┌───────────────────────────────────────┐  │  │  │
│  │  │  │  Entities   (business rules)          │  │  │  │
│  │  │  └───────────────────────────────────────┘  │  │  │
│  │  └─────────────────────────────────────────────┘  │  │
│  └───────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────┘

        Source code dependencies ALWAYS point inward

Source code dependencies can only point inwards. An inner circle knows nothing about the existence of an outer one - it doesn't import its classes, doesn't use its names, doesn't know its types.

Circle What it contains Example in .NET
Entities Enterprise-wide business rules, domain objects Order, Customer, Money, domain exceptions
Use Cases Application-specific rules, usage scenarios Command/query handlers, repository interfaces
Interface Adapters Conversion of data between use cases and the outside world Controllers, presenters, repository implementations
Frameworks & Drivers Technical details ASP.NET Core, EF Core, SQL Server, RabbitMQ, the file system

How is that possible, if a Use Case has to save data to the database?

This is where the Dependency Inversion Principle from SOLID comes in (discussed at the beginning of this site). The flow of control goes "outwards" (the handler calls the database), but the dependency in code is inverted:

Control flow:          Handler ───────────────► Database

Code dependencies:     Handler ──► IOrderRepository ◄── OrderRepository (EF Core)
                       (Application)  (Application)       (Infrastructure)

The IOrderRepository interface belongs to the inner layer (Application) - it dictates what it needs. The EF Core implementation lives on the outside and depends on the interface, not the other way round. This is exactly what a DI container does with Inversion of Control.

Mapping onto a .NET solution

In practice the circles turn into 4 projects (assemblies) in one solution. The references between projects enforce the dependency rule already at the compiler level:

Shop.sln
├── Shop.Domain           ← Entities (zero references to other projects)
├── Shop.Application      ← Use Cases (referencja: Domain)
├── Shop.Infrastructure   ← EF Core, external services (references: Application, Domain)
└── Shop.WebApi           ← Presentation + Composition Root (referencje: Application, Infrastructure)
        WebApi ─────────┬──────────► Application ──────► Domain
           │            │                 ▲
           └────────► Infrastructure ─────┘
              (tylko do rejestracji DI)
Project Contents What is NOT here
Domain Entities, value objects, enums, domain exceptions, domain events EF Core, ASP.NET, JSON, any "technical" NuGet packages
Application Commands/queries and handlers, interfaces (IOrderRepository, IEmailSender, IUnitOfWork), DTOs, validators, mappings Data access implementations, controllers, DbContext
Infrastructure DbContext, EF configurations, repositories, HTTP clients, IEmailSender implementations, Kafka/RabbitMQ Business logic
WebApi Controllers / minimal API, middleware, Program.cs (the Composition Root) Business logic, direct use of DbContext

The WebApi layer is the only one that "sees everything" - because it assembles the application into a whole (the Composition Root), registering the implementations in the DI container. Concrete infrastructure classes must not be created anywhere else.

A full example - creating an order

Domain - an entity with business rules

namespace Shop.Domain.Orders;

public class Order
{
    private readonly List<OrderItem> _items = new();

    public int Id { get; private set; }
    public string CustomerName { get; private set; } = default!;
    public IReadOnlyCollection<OrderItem> Items => _items.AsReadOnly();
    public decimal TotalAmount => _items.Sum(i => i.UnitPrice * i.Quantity);

    private Order() { } // wymagany przez EF Core, ale nie "przecieka" do reszty kodu

    public Order(string customerName)
    {
        if (string.IsNullOrWhiteSpace(customerName))
            throw new DomainException("Nazwa klienta jest wymagana.");

        CustomerName = customerName;
    }

    // Business rules live IN the entity, not in a service or a controller
    public void AddItem(string productName, decimal unitPrice, int quantity)
    {
        if (quantity <= 0)
            throw new DomainException("Quantity must be greater than zero.");

        _items.Add(new OrderItem(productName, unitPrice, quantity));
    }
}

This is an aggregate root (more in the "Aggregates" section below). Note: no using Microsoft.EntityFrameworkCore, no [Key]/[Table] attributes. The mapping configuration is in Infrastructure (Fluent API). The entity has private setters and protects its invariants - it is not a "bag of data" (an anemic model).

Application - interfaces (ports) and a use case

namespace Shop.Application.Orders;

// PORT - Application says what it needs; it knows nothing about EF Core
public interface IOrderRepository
{
    Task AddAsync(Order order, CancellationToken ct);
    Task<Order?> GetByIdAsync(int id, CancellationToken ct);
}

public interface IUnitOfWork
{
    Task<int> SaveChangesAsync(CancellationToken ct);
}

public record OrderItemDto(string ProductName, decimal UnitPrice, int Quantity);

public record CreateOrderCommand(string CustomerName, List<OrderItemDto> Items) : IRequest<int>;

public class CreateOrderHandler : IRequestHandler<CreateOrderCommand, int>
{
    private readonly IOrderRepository _orders;
    private readonly IUnitOfWork _unitOfWork;

    public CreateOrderHandler(IOrderRepository orders, IUnitOfWork unitOfWork)
    {
        _orders = orders;
        _unitOfWork = unitOfWork;
    }

    public async Task<int> Handle(CreateOrderCommand command, CancellationToken ct)
    {
        var order = new Order(command.CustomerName);

        foreach (var item in command.Items)
            order.AddItem(item.ProductName, item.UnitPrice, item.Quantity);

        await _orders.AddAsync(order, ct);
        await _unitOfWork.SaveChangesAsync(ct);

        return order.Id;
    }
}

This is a classic Use Case - it orchestrates the scenario (create, add items, save), but the business rules themselves stay in the entity. The handler uses MediatR (see MediatR - how it works and how to use it), although Clean Architecture itself doesn't require MediatR - it is just a convenient way to implement use cases.

Infrastructure - technical details

namespace Shop.Infrastructure.Persistence;

public class AppDbContext : DbContext, IUnitOfWork
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
        => modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
}

// Konfiguracja mapowania tutaj, a nie atrybutami w encji Domain
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasKey(o => o.Id);
        builder.Property(o => o.CustomerName).HasMaxLength(200).IsRequired();
        builder.OwnsMany(o => o.Items);
    }
}

public class OrderRepository : IOrderRepository
{
    private readonly AppDbContext _context;
    public OrderRepository(AppDbContext context) => _context = context;

    public async Task AddAsync(Order order, CancellationToken ct)
        => await _context.Orders.AddAsync(order, ct);

    public Task<Order?> GetByIdAsync(int id, CancellationToken ct)
        => _context.Orders.Include(o => o.Items).FirstOrDefaultAsync(o => o.Id == id, ct);
}

DbContext implements IUnitOfWork with no additional code - its SaveChangesAsync(CancellationToken) method matches the interface signature. This is the same Repository + Unit of Work pattern we discussed with EF Core.

Registering dependencies - each layer exposes its own method

// Shop.Application
public static class DependencyInjection
{
    public static IServiceCollection AddApplication(this IServiceCollection services)
    {
        services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(typeof(DependencyInjection).Assembly));
        return services;
    }
}

// Shop.Infrastructure
public static class DependencyInjection
{
    public static IServiceCollection AddInfrastructure(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddDbContext<AppDbContext>(o => o.UseSqlServer(configuration.GetConnectionString("Default")));
        services.AddScoped<IOrderRepository, OrderRepository>();
        services.AddScoped<IUnitOfWork>(sp => sp.GetRequiredService<AppDbContext>());
        return services;
    }
}

WebApi - a thin presentation layer and the Composition Root

// Program.cs - the ONLY place that knows all the layers
builder.Services.AddApplication();
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddControllers();
[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    private readonly ISender _sender; // MediatR
    public OrdersController(ISender sender) => _sender = sender;

    [HttpPost]
    public async Task<IActionResult> Create(CreateOrderCommand command, CancellationToken ct)
    {
        var id = await _sender.Send(command, ct);
        return Created($"api/orders/{id}", new { id });
    }
}

The controller is thin - it has no logic, it only translates an HTTP request into a command and the result into an HTTP response. Thanks to this it can be replaced (gRPC, a queue, a console application, WPF) without touching Application and Domain.

The flow of a single request

HTTP POST /api/orders
   │
   ▼
OrdersController (WebApi)                 ← translates HTTP into a command
   │  _sender.Send(command)
   ▼
CreateOrderHandler (Application)          ← orkiestruje use case
   │  new Order(...), order.AddItem(...)  ← rules in the entity (Domain)
   │  _orders.AddAsync(order)             ← call through the INTERFACE
   ▼
OrderRepository (Infrastructure)          ← EF Core, SQL
   │
   ▼
Baza danych

Only simple data crosses layer boundaries (DTOs, commands, simple types), not EF entities or framework objects. Domain entities don't go out to the HTTP client - the controller returns a DTO (mapped by hand or with AutoMapper), so that a change to the domain model doesn't break the API contract.

Aggregates - consistency boundaries in the Domain layer

The Order entity from the example above is actually an aggregate root - a concept from Domain-Driven Design that fits Clean Architecture very well, because it describes how to organise the inside of the Domain layer.

An aggregate is a group of related domain objects treated as one whole when changing data and enforcing business rules. One object is the root - only through it may anything be changed from the outside. The other objects (here OrderItem) are parts of the aggregate and have no life outside it.

┌─────────────── Agregat Order ───────────────┐
│                                             │
│   Order  (Aggregate Root)                   │
│    ├── OrderItem                            │
│    ├── OrderItem                            │
│    └── OrderItem                            │
│                                             │
└─────────────────────────────────────────────┘
        ▲                          │
        │ the only entry point     │ reference by Id,
        │ from outside             ▼ not by reference
   IOrderRepository          CustomerId ──► (inny agregat: Customer)

Aggregate rules

Rule What it means in practice
Access only through the root There is no order.Items.Add(...) from outside and no separate OrderItemRepository. Changes go through methods of the root (order.AddItem(...)), which checks the rules
Consistency boundary After every operation the whole aggregate is consistent (e.g. the order total matches the items, a confirmed order can no longer be changed)
One transaction = one aggregate You save and lock the aggregate as a whole. If one operation has to change two aggregates, it's a sign the boundaries are drawn wrongly or that you need domain events
References to other aggregates by Id Order holds CustomerId, not a Customer object. Aggregates stay small and don't drag half the database along with them
One repository per aggregate The repository concerns the root: IOrderRepository, not IOrderItemRepository
Small aggregates A huge aggregate (e.g. Customer with all orders inside) means slow queries and concurrency conflicts

An example - the aggregate root guards the invariants

namespace Shop.Domain.Orders;

public class Order : Entity
{
    private readonly List<OrderItem> _items = new();

    public int Id { get; private set; }
    public int CustomerId { get; private set; }          // reference to another aggregate by Id
    public OrderStatus Status { get; private set; } = OrderStatus.Draft;
    public IReadOnlyCollection<OrderItem> Items => _items.AsReadOnly();   // brak publicznej listy do modyfikacji
    public decimal TotalAmount => _items.Sum(i => i.UnitPrice * i.Quantity);

    private Order() { }

    public Order(int customerId) => CustomerId = customerId;

    public void AddItem(string productName, decimal unitPrice, int quantity)
    {
        // Invariant: a confirmed order may no longer be changed
        if (Status != OrderStatus.Draft)
            throw new DomainException("A confirmed order cannot be changed.");

        if (quantity <= 0)
            throw new DomainException("Quantity must be greater than zero.");

        _items.Add(new OrderItem(productName, unitPrice, quantity));
    }

    public void Confirm()
    {
        // Invariant: an order without items makes no sense
        if (_items.Count == 0)
            throw new DomainException("An order must have at least one item.");

        Status = OrderStatus.Confirmed;
        Raise(new OrderConfirmedEvent(Id));              // information for other aggregates
    }
}

The OrderItem class has an internal constructor (or is nested), so nobody outside Domain can create an item bypassing the order. The rules "a confirmed order is immutable" and "there is no empty order" have one place - in the root - instead of being scattered across handlers and controllers.

Communication between aggregates - domain events

When confirming an order is supposed to affect another aggregate (e.g. reserve stock in Product), you don't change both in one transaction. The root raises a domain event, and the reaction happens separately:

// Domain - events don't depend on any library
public interface IDomainEvent { }
public record OrderConfirmedEvent(int OrderId) : IDomainEvent;

public abstract class Entity
{
    private readonly List<IDomainEvent> _events = new();
    public IReadOnlyCollection<IDomainEvent> DomainEvents => _events.AsReadOnly();

    protected void Raise(IDomainEvent domainEvent) => _events.Add(domainEvent);
    public void ClearDomainEvents() => _events.Clear();
}

Events are dispatched after a successful save (typically in SaveChangesAsync in Infrastructure, e.g. through MediatR INotification), and a handler in Application changes the second aggregate in a separate transaction. This is exactly eventual consistency - consistency between aggregates is not immediate. For communication between services, the same idea is developed further by the Saga and Outbox patterns described in the section on distributed architecture.

What an aggregate looks like on the Application and Infrastructure side

// Application - the handler loads the aggregate, calls its methods, saves the whole
public async Task Handle(ConfirmOrderCommand command, CancellationToken ct)
{
    var order = await _orders.GetByIdAsync(command.OrderId, ct)
                ?? throw new NotFoundException(nameof(Order), command.OrderId);

    order.Confirm();                              // the root checks the rules, not the handler

    await _unitOfWork.SaveChangesAsync(ct);       // jedna transakcja = jeden agregat
}
// Infrastructure - konfiguracja EF Core respektuje granice agregatu
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasKey(o => o.Id);
        builder.OwnsMany(o => o.Items);                       // items are PART of the aggregate
        builder.Property<byte[]>("RowVersion").IsRowVersion(); // optimistic concurrency on the whole aggregate
    }
}
  • GetByIdAsync loads the whole aggregate (Include(o => o.Items)), not a fragment - thanks to this the root sees all the data needed to check the invariants.
  • RowVersion protects against two users changing the same aggregate at the same time - the second save gets a DbUpdateConcurrencyException instead of silently overwriting someone else's changes.

Typical mistakes with aggregates

  • A public list modifiable from outside (public List<OrderItem> Items { get; set; }) - the root loses control and the rules can be bypassed. Expose IReadOnlyCollection<T>.
  • A giant aggregate - Customer containing all orders, addresses and payments. Every change locks and loads the whole thing. Split into smaller aggregates linked by Id.
  • References to objects of other aggregates instead of Ids - they pull half the database into queries and blur transaction boundaries.
  • Changing many aggregates in one transaction - breaks the one-transaction-per-aggregate rule; domain events are usually better.
  • Logic outside the root - if the rules sit in handlers and entities are just getters and setters, the aggregate is only a name (an anemic model).
  • Aggregates "just in case" in simple CRUD - without complex invariants DDD is overkill.

Testability - the main benefit in practice

Testing a use case without a database

public class CreateOrderHandlerTests
{
    [Fact]
    public async Task Handle_ValidCommand_AddsOrderAndSaves()
    {
        var repository = new Mock<IOrderRepository>();
        var unitOfWork = new Mock<IUnitOfWork>();
        var handler = new CreateOrderHandler(repository.Object, unitOfWork.Object);

        var command = new CreateOrderCommand(
            "Jan Kowalski",
            new List<OrderItemDto> { new("Laptop", 3000m, 1) });

        await handler.Handle(command, CancellationToken.None);

        repository.Verify(r => r.AddAsync(
            It.Is<Order>(o => o.CustomerName == "Jan Kowalski"),
            It.IsAny<CancellationToken>()), Times.Once);
        unitOfWork.Verify(u => u.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once);
    }
}

The test is fast (milliseconds), and doesn't need SQL Server or WebApplicationFactory. The rules of the entity itself (Order.AddItem throws for a quantity ≤ 0) are tested even more simply - pure C# code without any mocks.

An architecture test - guarding the dependency rule

The project structure alone protects against most violations, but not all (e.g. someone adds a reference "because it's quicker"). The NetArchTest library lets you write the rule as a test:

[Fact]
public void Domain_ShouldNotDependOn_OtherLayers()
{
    var result = Types.InAssembly(typeof(Order).Assembly)
        .ShouldNot()
        .HaveDependencyOnAny("Shop.Application", "Shop.Infrastructure", "Shop.WebApi")
        .GetResult();

    Assert.True(result.IsSuccessful);
}

Thanks to this, an architecture violation breaks the build in CI instead of only surfacing in code review.

Clean Architecture compared with other approaches

Layered architecture (N-tier) Hexagonal / Onion Clean Architecture Vertical Slice
Direction of dependencies UI → Logic → Data access (logic depends on the database) Inwards (domain in the centre) Inwards (the dependency rule) Depends on the slice
Centre of the system The database The domain model Entities + Use Cases The feature
Division of code By technical layers By layers, ports and adapters By layers (circles) By features
Use case layer Usually blurred into "Services" Not distinguished Explicit, separate Inside the slice
Typical cost Few files, a rigid database Medium More projects and interfaces A lot of duplication between slices

The key difference compared with classic three-tier architecture: there, the business layer depends on the data access layer (the BLL references the DAL), so a change of database or ORM leaks into the logic. In Clean Architecture the dependency is inverted - infrastructure depends on Application.

Typical mistakes and criticism

1. Overkill for simple CRUD. An application that only saves and reads forms has no "business rules" to protect. Four projects, 1:1 interfaces and a handler for every operation are then pure overhead. For small projects a simpler structure is enough.

2. Anemic Domain Model. Entities are just getters and setters, and all the logic sits in handlers - then "Domain" is an empty layer and the architecture loses its point.

3. Leaking IQueryable through the repository. If IOrderRepository returns IQueryable<Order>, the Application layer starts to depend on the behaviour of a specific EF provider (which operations can be translated to SQL). That is a broken abstraction.

4. EF entities as domain entities - a pragmatic compromise. The pure version requires separate models (domain and persistence) with mapping between them. In most .NET projects it is accepted that domain entities are at the same time mapped by EF (with the configuration in Infrastructure). This is a conscious compromise, not a mistake, but it's worth knowing it exists.

5. A repository over EF Core - a dispute. DbContext already is a Unit of Work, and DbSet is a repository. Some teams give up their own repositories and define an IApplicationDbContext interface with DbSet<T> in Application, implemented in Infrastructure. They gain less code and lose "purity" (Application knows DbSet/IQueryable). This is the same topic as the controversy around Repository + Unit of Work.

6. Thoughtless creation of interfaces. An interface makes sense where there is a boundary (the database, an external API, mail). An interface for a class that has one implementation and lives inside one layer is redundant.

7. Logic in the controller or in Infrastructure. The most common violation: validation and calculations end up in the controller or the repository, because "it was quicker".

When it makes sense

Situation Clean Architecture?
An application with elaborate business rules (finance, logistics, insurance) ✅ Yes - this is where it gives the biggest benefit
A system developed for years by several teams ✅ Yes - layer boundaries bring order to the work
High unit-test coverage of the logic is required ✅ Yes
A possible change of technology (database, UI) is planned ✅ Yes
Simple CRUD, a prototype, an internal tool ❌ Usually overkill
A microservice with one narrow responsibility ⚠️ A simplified version or Vertical Slice is often enough

Clean Architecture and CQRS - where they meet

In Clean Architecture the Application layer consists of use cases, and the most convenient way to write them down is commands and queries - exactly what the CQRS pattern describes. The details of the pattern (separating the write and read models, eventual consistency, Event Sourcing) are in separate topics:

How this fits with the layers:

Side What it does Which way it goes
Command (write) Changes state, returns at most an Id or the result of the operation Handler → aggregate in Domain (business rules) → repository → save in one transaction
Query (read) Doesn't change state, returns a DTO Handler → directly to the database (projection to a DTO) - without loading aggregates

The write side goes through the domain model, because the invariants live there (cf. the section on aggregates). The read side has nothing to protect, so it can bypass it and read data by the shortest path. The interface for such a read also belongs to Application, and the implementation to Infrastructure:

// Application - a port for reads, without aggregates and without EF Core
public interface IOrderQueries
{
    Task<OrderDetailsDto?> GetDetailsAsync(int id, CancellationToken ct);
}

public record GetOrderQuery(int Id) : IRequest<OrderDetailsDto?>;

public class GetOrderHandler : IRequestHandler<GetOrderQuery, OrderDetailsDto?>
{
    private readonly IOrderQueries _queries;
    public GetOrderHandler(IOrderQueries queries) => _queries = queries;

    public Task<OrderDetailsDto?> Handle(GetOrderQuery query, CancellationToken ct)
        => _queries.GetDetailsAsync(query.Id, ct);
}
// Infrastructure - a fast projection to a DTO, without change tracking
public class OrderQueries : IOrderQueries
{
    private readonly AppDbContext _context;
    public OrderQueries(AppDbContext context) => _context = context;

    public Task<OrderDetailsDto?> GetDetailsAsync(int id, CancellationToken ct)
        => _context.Orders
            .AsNoTracking()
            .Where(o => o.Id == id)
            .Select(o => new OrderDetailsDto(o.Id, o.CustomerId, o.Status.ToString(), o.Items.Sum(i => i.UnitPrice * i.Quantity)))
            .FirstOrDefaultAsync(ct);
}

Thanks to this, the repository (IOrderRepository) handles only aggregates on the write side, and reads go through a separate path - this is a common, pragmatic compromise in Clean Architecture that doesn't require separate databases (that is already the level of "full" CQRS). An extra benefit of MediatR: pipeline behaviors let you add validation, logging or a transaction to all use cases in one place.

Connections to other topics on this site

  • SOLID / DIP - the dependency rule is the Dependency Inversion Principle applied at the scale of the whole application,
  • IoC and DI - the DI container in the Composition Root wires the layers together, thanks to which Application doesn't create infrastructure itself,
  • CQRS and MediatR - use cases naturally take the form of commands and queries with handlers: What CQRS is, MediatR,
  • Repository + Unit of Work - interfaces in Application, implementations in Infrastructure,
  • Aggregates and DDD - organising the inside of the Domain layer: the aggregate root guards invariants, one repository per aggregate,
  • Saga and Outbox - extending communication between aggregates (events) to the level of many services,
  • AutoMapper - mapping entities to DTOs at the layer boundary,
  • Tests (xUnit, Moq) - Application is tested with mocks of ports, without a database.

How to answer in an interview

The question asked in an interview is usually: "What is Clean Architecture and how does it differ from ordinary layered architecture?"

"Clean Architecture organises code into concentric circles - domain entities in the middle, then use cases, adapters and finally technical details such as the database or the web framework. The most important thing is the dependency rule: dependencies in code point only inwards, so business logic knows nothing about EF Core, ASP.NET or the database. This is achieved by inverting dependencies - Application defines interfaces, for example a repository, and Infrastructure implements them, with the whole thing wired up by a DI container in the Composition Root. In classic three-tier architecture the business layer depends on the data layer, here it is the opposite. I gain testability and the ability to replace technical details, and I pay with more projects and interfaces, so in simple CRUD I wouldn't use it."

A good answer shows three things: that you understand the direction of dependencies (not just the names of layers), that you know how to achieve it in .NET (DIP, DI, separate projects), and that you know the cost of this approach and can judge when it doesn't pay off.

Summary

Clean Architecture places business logic at the centre of the application and subordinates all technical details to it with one rule: dependencies in code point only inwards. In .NET this is implemented with four projects (Domain, Application, Infrastructure, WebApi), interfaces defined in the inner layer and implemented on the outside (Dependency Inversion), and a DI container wiring everything together in the Composition Root. The inside of the Domain layer is organised by aggregates - groups of objects with one root that guards the invariants, saved in one transaction, linked to other aggregates by Id and domain events. You gain testability of use cases without a database, replaceable frameworks and protection of business rules, and you pay with more code and projects - so it pays off with a complex domain and long-lived systems, and in simple CRUD it is overkill.

Buy me a coffee