All articles

What Is Clean Architecture, and When Should You Use It?

Explore the principles, layers, and dependency structure of Clean Architecture with practical ASP.NET Core examples. Learn when it provides real value, when it adds unnecessary complexity, and how to choose the right architecture for a project.

What Is Clean Architecture, and When Should You Use It?

Creating an order in an ASP.NET Core application requires an endpoint to receive the request, code to enforce business rules, and a database write. Initially, these steps may fit into just a few files. As the application grows, however, replacing a payment provider, introducing a new business rule, or updating the database schema can affect an unexpectedly large number of components.

Clean Architecture is a software architecture approach intended, among other things, to limit the impact of such changes. Its primary goal is to keep an application's business rules as independent as possible from technical details such as databases, web frameworks, and external services. However, introducing the same number of layers and abstractions into every project is not necessarily a sound investment.

In this article, we will examine how Clean Architecture works, how it can be implemented in .NET, when it provides value, and when it adds unnecessary cost, using a concrete order-creation example.

What is Clean Architecture?

Clean Architecture is an architectural approach that puts an application's core business behavior at the center and directs source-code dependencies toward that center. At the core are rules governing when an order can be created, how discounts are calculated, or which state transitions are permitted. Outside are implementation details such as HTTP, Entity Framework Core, PostgreSQL, email providers, and similar technologies.

This separation is primarily logical rather than physical. Splitting an application into four separate projects does not automatically make it Clean Architecture. Conversely, an application deployed as a single unit can benefit from these principles if it maintains the right boundaries.

The fundamental design question is: When a technical component changes, must we also change a business rule? For example, if upgrading a payment provider's SDK should not change the conditions under which an order is considered valid, separating these responsibilities makes sense.

Clean Architecture does not eliminate dependencies. It controls which layers know about which contracts and the direction in which changes can propagate.

How does Clean Architecture work?

The Dependency Rule

At the heart of the approach is the Dependency Rule: source-code dependencies should point inward, from outer technical details toward inner business policies. Inner layers should not depend on concrete classes defined in outer layers.

In a typical ASP.NET Core solution, this relationship can be summarized as follows:

API / Presentation ──▶ Application ──▶ Domain
Infrastructure ──────▶ Application / Domain

The arrows represent compile-time project and type dependencies, not the order in which requests execute at runtime. Application does not directly reference an EF Core repository class inside Infrastructure. Instead, it defines the behavior it needs through an interface, and the concrete repository implements that interface in the outer layer.

At runtime, the call sequence looks different: the API passes a request to an application use case, the use case calls a repository through its interface, and the repository accesses the database. The application can therefore perform its work while preserving the opposite direction of source-code dependencies.

Interfaces and dependency injection

Suppose an IOrderRepository interface lives in the Application layer while its EfOrderRepository implementation lives in Infrastructure. ASP.NET Core's dependency injection (DI) system connects the two at startup.

Here, DI is a tool; choosing the direction of dependencies is an architectural decision. Adding an interface to every class or routing every method through a service is not a requirement of Clean Architecture. An abstraction is valuable when it represents a boundary worth protecting.

Clean Architecture layers

Domain: The center of business rules

The Domain layer contains business concepts, behaviors, and invariants: conditions that must always hold. Examples include requiring a valid order total, determining when an order may be canceled, and defining the rules for applying discounts.

A Domain model should not require an HTTP request, a DbContext, or an SDK type from a payment provider to make a business decision. This allows business behavior to be tested independently of the technical infrastructure.

Application: Use cases

The Application layer coordinates what a user or system is trying to do, such as creating an order, initiating a payment, or renewing a subscription. It manages the sequence of operations, invokes Domain rules, and requests the required external behavior through interfaces.

The important distinction is that Domain determines what is valid; Application determines how a use case is executed. If a policy belongs to the Domain, the Application layer should not reimplement the same rule.

Infrastructure: Technical implementations

The Infrastructure layer implements details such as database access, file storage, message queues, and third-party API connections. An EF Core DbContext, repository implementations, and external-service clients can live here.

Introducing an interface does not remove infrastructure costs. SQL queries, transaction boundaries, failure behavior, and provider-specific capabilities still need to be designed and verified through real integration tests.

API / Presentation: Communication with the outside world

API / Presentation receives HTTP requests, validates input, performs authorization, and converts outcomes into appropriate HTTP responses. Business rules should not all be moved into controllers or endpoints.

In ASP.NET Core, Program.cs often serves as the composition root. Referencing Infrastructure from the API project to register concrete implementations with DI at startup is a practical and acceptable exception; the rest of the business flow should not depend on concrete infrastructure classes.

These four layer names are common, but they are not a mandatory template. The number of projects and the file organization should reflect the complexity of the actual business domain.

Implementing Clean Architecture with ASP.NET Core

Consider an order-creation use case. We will make a few simple assumptions: the order has an identifier, its total amount must be greater than zero, and a valid order must be persisted to the database. This is a deliberately limited example designed to illustrate architectural dependencies, not a complete e-commerce or production-ready ordering system.

1. Domain rule

The order's validity constraints are enforced in the Domain:

namespace Shop.Domain;

public sealed class Order
{
    public Guid Id { get; private set; }
    public decimal Total { get; private set; }

    private Order(Guid id, decimal total)
    {
        Id = id;
        Total = total;
    }

    public static Order Create(Guid id, decimal total)
    {
        if (id == Guid.Empty)
            throw new ArgumentException("Invalid order identifier.", nameof(id));

        if (total <= 0)
            throw new ArgumentOutOfRangeException(nameof(total));

        return new Order(id, total);
    }
}

This class needs neither ASP.NET Core nor EF Core to enforce its business rule. Private setters and a private constructor matching the properties can allow EF Core to materialize the object; its publicly exposed behavior remains controlled by the Domain.

2. Application use case

The Application layer does not need to know how data is stored; it needs a component capable of storing it:

using Shop.Domain;

namespace Shop.Application;

public interface IOrderRepository
{
    Task AddAsync(Order order, CancellationToken cancellationToken);
}

public sealed class CreateOrder
{
    private readonly IOrderRepository _orders;

    public CreateOrder(IOrderRepository orders) => _orders = orders;

    public async Task<Guid> ExecuteAsync(
        decimal total, CancellationToken cancellationToken)
    {
        var order = Order.Create(Guid.NewGuid(), total);
        await _orders.AddAsync(order, cancellationToken);
        return order.Id;
    }
}

CreateOrder contains no SQL command, connection string, or EF Core type. The order-creation behavior can be executed outside an HTTP endpoint as well.

3. Connecting Infrastructure and API

The EF Core implementation conforms to the interface defined in the inner layer:

using Microsoft.EntityFrameworkCore;
using Shop.Application;
using Shop.Domain;

namespace Shop.Infrastructure;

public sealed class ShopDbContext : DbContext
{
    public ShopDbContext(DbContextOptions<ShopDbContext> options)
        : base(options) { }

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>(entity =>
        {
            entity.HasKey(x => x.Id);
            entity.Property(x => x.Total).HasPrecision(18, 2);
        });
    }
}

public sealed class EfOrderRepository : IOrderRepository
{
    private readonly ShopDbContext _db;

    public EfOrderRepository(ShopDbContext db) => _db = db;

    public async Task AddAsync(Order order, CancellationToken ct)
    {
        _db.Orders.Add(order);
        await _db.SaveChangesAsync(ct);
    }
}

In the API project, Program.cs brings the application and infrastructure components together using DI:

using Microsoft.EntityFrameworkCore;
using Shop.Application;
using Shop.Infrastructure;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ShopDbContext>(options =>
    options.UseNpgsql(
        builder.Configuration.GetConnectionString("Shop")
        ?? throw new InvalidOperationException("Shop connection string is not configured.")));

builder.Services.AddScoped<IOrderRepository, EfOrderRepository>();
builder.Services.AddScoped<CreateOrder>();

var app = builder.Build();

app.MapPost("/orders", async (
    CreateOrderRequest request, CreateOrder useCase, CancellationToken ct) =>
{
    if (request.Total <= 0)
        return Results.BadRequest(new { error = "Invalid order total." });

    var id = await useCase.ExecuteAsync(request.Total, ct);
    return Results.Created($"/orders/{id}", new { id });
});

app.Run();

public sealed record CreateOrderRequest(decimal Total);

The project dependencies in this example are Application → Domain, Infrastructure → Application + Domain, and API → Application. The API also knows about Infrastructure types solely for the initial DI registration. Connecting to PostgreSQL additionally requires the EF Core provider, an appropriate connection-string configuration, and a database schema.

A production environment has important requirements not shown here: authentication and resource-based authorization, input validation, idempotency (handling repeated requests), error responses, observability, and appropriate transaction boundaries. Copying this example alone does not create a production-ready ordering system.

4. Testability

One of the first concrete benefits of the dependency direction is the ability to test business behavior without starting a database. For example, the following test verifies the CreateOrder use case using an in-memory fake repository:

using Shop.Application;
using Shop.Domain;
using Xunit;

public sealed class CreateOrderTests
{
    [Fact]
    public async Task Valid_order_is_saved()
    {
        var repository = new FakeOrderRepository();
        var useCase = new CreateOrder(repository);

        var id = await useCase.ExecuteAsync(125m, CancellationToken.None);

        Assert.Equal(id, repository.Stored?.Id);
        Assert.Equal(125m, repository.Stored?.Total);
    }

    [Fact]
    public async Task Invalid_total_is_rejected()
    {
        var repository = new FakeOrderRepository();
        var useCase = new CreateOrder(repository);

        await Assert.ThrowsAsync<ArgumentOutOfRangeException>(
            () => useCase.ExecuteAsync(0m, CancellationToken.None));

        Assert.Null(repository.Stored);
    }

    private sealed class FakeOrderRepository : IOrderRepository
    {
        public Order? Stored { get; private set; }

        public Task AddAsync(Order order, CancellationToken ct)
        {
            Stored = order;
            return Task.CompletedTask;
        }
    }
}

This test verifies Domain and Application behavior; it does not prove that the EF Core mapping, SQL, or real transaction works correctly. Those aspects require integration tests against a real database. Authorization and the HTTP contract also require separate API tests.

When should you use Clean Architecture?

Clean Architecture is particularly useful when business rules matter, the cost of change is high, and the application is expected to live for a long time.

  • Complex business rules: Behaviors such as order states, discount conditions, payment collection rules, or different authorization levels must be enforced consistently across multiple screens and operations.

  • Changing external systems: Use cases should remain stable when payment, email, file-storage, or enterprise-system integrations are updated.

  • Continuously evolving products: Clear dependency boundaries are valuable in systems developed by several engineers and expected to gain features over many years.

  • Strong testing requirements: When business rules have many conditions, separating fast unit tests from real infrastructure tests can simplify development and debugging.

These conditions do not all need to be present. What matters is whether the proposed separation reduces a real risk related to change or maintenance.

When does it add unnecessary complexity?

For a short-lived administrative tool made up of simple CRUD screens, a small prototype, or an application with limited business behavior, four projects, numerous interfaces, and separate DTO layers may be unnecessary.

For example, a tool that displays records from one database, updates a few fields, and has no meaningful domain rules may only need a straightforward ASP.NET Core structure. You can start with an endpoint or controller, an appropriate service, and a clear data-access boundary, then strengthen the boundaries as the rules grow.

Conversely, a payment operation presented on a single screen may benefit from Clean Architecture if its business rules and failure conditions are complex. The decision should be based on the complexity of behavior and change, not the number of screens or files.

Benefits, costs, and limitations

Benefits

  • Limits the impact of change: It can reduce the spread of technical integration changes into Domain and Application.

  • Makes business rules visible: Critical behavior is less likely to become scattered between endpoints and data-access code.

  • Separates testing concerns: Fast business-behavior tests and database, HTTP, and external-service tests can serve distinct purposes.

  • Clarifies responsibilities: New developers can more easily understand where a rule or integration belongs.

Costs and trade-offs

  • More files and abstractions: A simple feature may require an interface, use case, adapter, and data transformations.

  • Harder execution tracing: Following a request through several layers can increase the initial cost, especially for small teams.

  • Boundaries require maintenance: Correct layer names do not deliver the intended benefits if business rules are spread into controllers or SQL queries.

  • Cost of inappropriate abstractions: Adding interfaces to components that are unlikely to change merely to follow a template can make code more indirect rather than more flexible.

Problems it does not solve

Clean Architecture alone does not guarantee performance, security, scalability, or data consistency. A slow SQL query does not become faster because the code is divided into layers. If two concurrent requests try to consume the same inventory, Domain validation may need to be complemented by database concurrency controls. Reliably combining a database operation with an external message may require mechanisms such as the outbox pattern.

Exposing infrastructure behavior such as IQueryable directly to inner layers can also leak technical dependencies, even through interfaces. Contracts should express meaningful operations required by use cases; generating a generic repository for every table is not mandatory.

How does it differ from related approaches?

The concepts often mentioned alongside Clean Architecture are not all alternatives at the same architectural level:

  • Layered Architecture: Separates responsibilities such as presentation, business logic, and data access. Clean Architecture's distinguishing principle is directing source-code dependencies toward business rules. The approaches can overlap.

  • Hexagonal Architecture (Ports & Adapters): Describes interaction with the outside world through ports and adapters. It shares major principles with Clean Architecture; a separate article is better suited to exploring port types and adapter design in detail.

  • Onion Architecture: Keeps the domain model at the center and directs dependencies inward. It belongs to a closely related family of designs.

  • Domain-Driven Design (DDD): Focuses on modeling a complex business domain and defining its boundaries. It can be used alongside Clean Architecture, but neither is a prerequisite for the other.

  • CQRS: Separates read and write models or processing paths. It can be used within Clean Architecture, but it is not required and may add complexity to a simple use case.

  • Modular Monoliths and Microservices: Address boundaries between modules or services and how software is deployed. Clean Architecture primarily organizes source-code dependencies. It can be applied within a monolith or inside an individual microservice.

Therefore, adopting Clean Architecture does not require MediatR, CQRS, microservices, or a particular .NET template. Libraries and project structures are not substitutes for architecture.

How should you decide for your project?

A practical decision process is more useful than starting with a template:

  1. Identify the business rules. Do they amount to simple input validation, or must behavior remain consistent across different states and operations?

  2. Make expected changes concrete. Which integrations, use cases, or business policies are genuinely likely to change? Distinguish confirmed requirements from possibilities.

  3. Measure the current impact of dependencies. How many modules does one change affect? Which external systems must be started to test the code? If you lack this evidence, observe the system first.

  4. Establish the smallest useful boundary. Start by separating an important domain rule from the use case that invokes it. Define a port for an external dependency when needed. Do not abstract every class in advance.

  5. Protect boundaries with tests and CI. Verify that Domain does not reference Infrastructure; write unit tests for business rules and integration tests for EF Core and HTTP behavior.

  6. Monitor maintenance costs. Is it easier to add features? Are unnecessary mappings and interface layers growing? Let real change requirements guide the architecture's evolution.

This assessment can lead to three different outcomes. A simple, short-lived record-management tool may only need straightforward layering. A long-lived product with extensive business rules and several external systems can benefit substantially from Clean Architecture boundaries. For an uncertain MVP, starting with a single deployment unit and limited abstractions, then refining the layers when the need is demonstrated, is often a more balanced approach.

How an architecture is verified and maintained matters as much as the architecture selected for the first release. Unit tests protect business rules, real infrastructure tests protect data and integration behavior, and CI checks protect dependency boundaries. Production observations, including failure rates, change scope, and maintenance time, help reveal whether the decision pays off.

Conclusion

The value of Clean Architecture comes not from creating four folders or projects, but from establishing boundaries that protect business rules from changing technical details. In complex, long-lived business applications, these boundaries can make development and testing more manageable. In simple applications, the same level of separation may introduce unnecessary cost.

Instead of asking, “Should we use Clean Architecture in every project?”, a better question is, “Which business rules do we need to protect from which changes in this project?” Once the answer is clear, choosing an appropriate level of layering and abstraction becomes easier.

For a broader overview of architectural approaches, selection criteria, and trade-offs, read How to Choose Software Architecture.