Clean Architecture with ASP.NET Core: A Practical Guide

Clean Architecture with ASP.NET Core: A Practical Guide
```html

What Is Clean Architecture and Why Should We Use It?

When building a small ASP.NET Core application, keeping everything in a single project can initially be very convenient. A controller can use Entity Framework Core directly, query the database, apply a few business rules and return the result.

A typical implementation may look like this:

[HttpPost]
public async Task<IActionResult> CreateOrder(
    CreateOrderRequest request)
{
    var product = await _db.Products
        .FirstOrDefaultAsync(
            x => x.Id == request.ProductId);

    if (product == null)
        return NotFound();

    if (product.StockQuantity < request.Quantity)
        return Conflict("Insufficient stock.");

    product.StockQuantity -= request.Quantity;

    var order = new Order
    {
        ProductId = product.Id,
        Quantity = request.Quantity,
        TotalAmount =
            product.Price * request.Quantity
    };

    _db.Orders.Add(order);

    await _db.SaveChangesAsync();

    return Ok(order);
}

This may work perfectly well for a small application. The problems usually begin as the system grows.

Over time, a controller may become responsible for:

  • Database access
  • Business rules
  • Email delivery
  • Payment integration
  • Logging
  • Transactions
  • DTO mapping

The HTTP layer becomes tightly coupled to business logic, persistence and external services.

The purpose of Clean Architecture is not to maximize the number of layers.

Its goal is to protect the application's most valuable part, its business rules, from volatile technical details such as frameworks, databases, user interfaces and external services.

1. The Core Problem: Business Logic Depends on Infrastructure

Traditional layered applications often use dependencies in this direction:

Web
 ↓
Business
 ↓
Data Access
 ↓
SQL Server

The Business layer may directly depend on concrete persistence implementations.

public class OrderService
{
    private readonly SqlOrderRepository _repository;

    public OrderService(
        SqlOrderRepository repository)
    {
        _repository = repository;
    }
}

OrderService now knows specifically about a SQL implementation.

Testing the business logic can therefore pull database and persistence concerns into the test.

Clean Architecture tries to reverse this dependency.

2. The Dependency Rule

The most important principle in Clean Architecture is:

Dependencies should point from outer layers toward the inner business layers.

Business logic should not depend on Infrastructure implementations. Infrastructure implements abstractions owned by the inner layers.

             Web / API
                │
                ▼
           Application
                │
                ▼
              Domain


Infrastructure ───────► Application
       │
       └──────────────► Domain

The Domain remains at the center.

SQL Server, Entity Framework Core, SMTP, Redis, RabbitMQ or any other infrastructure technology should not define the business model.

3. Example Solution Structure

Assume we are developing an order-management application.

CleanShop/
│
├── CleanShop.Domain/
│   ├── Entities/
│   ├── ValueObjects/
│   ├── Events/
│   └── Exceptions/
│
├── CleanShop.Application/
│   ├── DTOs/
│   ├── Interfaces/
│   ├── Orders/
│   └── Common/
│
├── CleanShop.Infrastructure/
│   ├── Persistence/
│   ├── Repositories/
│   ├── Integrations/
│   └── DependencyInjection.cs
│
├── CleanShop.Api/
│   ├── Controllers/
│   ├── Middleware/
│   └── Program.cs
│
├── CleanShop.UnitTests/
│
└── CleanShop.IntegrationTests/

This is not the only valid Clean Architecture structure.

The important part is not the folder names. The important part is separating responsibilities and controlling dependency direction.

4. Creating the Solution

dotnet new sln -n CleanShop

dotnet new classlib -n CleanShop.Domain -f net10.0
dotnet new classlib -n CleanShop.Application -f net10.0
dotnet new classlib -n CleanShop.Infrastructure -f net10.0
dotnet new webapi -n CleanShop.Api -f net10.0

dotnet sln add CleanShop.Domain
dotnet sln add CleanShop.Application
dotnet sln add CleanShop.Infrastructure
dotnet sln add CleanShop.Api

Add project references:

dotnet add CleanShop.Application reference CleanShop.Domain

dotnet add CleanShop.Infrastructure reference CleanShop.Domain
dotnet add CleanShop.Infrastructure reference CleanShop.Application

dotnet add CleanShop.Api reference CleanShop.Application
dotnet add CleanShop.Api reference CleanShop.Infrastructure

5. The Domain Layer

The Domain contains the core business model.

It should avoid unnecessary dependencies on ASP.NET Core, Entity Framework Core or other infrastructure frameworks.

Example Product entity:

public class Product
{
    public int Id { get; private set; }

    public string Name { get; private set; }
        = string.Empty;

    public decimal Price { get; private set; }

    public int StockQuantity { get; private set; }

    private Product()
    {
    }

    public Product(
        string name,
        decimal price,
        int stockQuantity)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new DomainException(
                "Product name is required.");

        if (price < 0)
            throw new DomainException(
                "Price cannot be negative.");

        if (stockQuantity < 0)
            throw new DomainException(
                "Stock cannot be negative.");

        Name = name;
        Price = price;
        StockQuantity = stockQuantity;
    }

    public void DecreaseStock(int quantity)
    {
        if (quantity <= 0)
            throw new DomainException(
                "Quantity must be greater than zero.");

        if (StockQuantity < quantity)
            throw new InsufficientStockException();

        StockQuantity -= quantity;
    }
}

Instead of allowing any part of the application to modify inventory freely, the entity protects its own business invariant.

6. Avoiding an Anemic Domain Model

Moving entity classes into a project named Domain does not automatically produce a rich domain model.

public class Product
{
    public int Id { get; set; }

    public decimal Price { get; set; }

    public int StockQuantity { get; set; }
}

If all business behavior remains in services, the entity is little more than a data structure.

This isn't necessarily wrong for simple CRUD applications.

For more complex business domains, placing important invariants and behavior inside entities and value objects can create a stronger model.

7. Order Entity

public class Order
{
    public long Id { get; private set; }

    public int ProductId { get; private set; }

    public int Quantity { get; private set; }

    public decimal UnitPrice { get; private set; }

    public decimal TotalAmount { get; private set; }

    public string Status { get; private set; }
        = "Created";

    public DateTime CreatedAt { get; private set; }

    private Order()
    {
    }

    public Order(
        int productId,
        int quantity,
        decimal unitPrice)
    {
        if (quantity <= 0)
            throw new DomainException(
                "Quantity must be greater than zero.");

        if (unitPrice < 0)
            throw new DomainException(
                "Unit price cannot be negative.");

        ProductId = productId;
        Quantity = quantity;
        UnitPrice = unitPrice;

        TotalAmount =
            quantity * unitPrice;

        CreatedAt =
            DateTime.UtcNow;
    }
}

8. What Belongs in the Application Layer?

The Application layer coordinates use cases initiated by users or external systems.

Examples include:

  • Create Order
  • Cancel Order
  • Get Order
  • Update Product Price

The Application layer coordinates business workflows, but it does not need to know how SQL Server connections or external APIs are implemented.

9. Where Should Repository Interfaces Live?

Suppose the Application layer needs Product data.

It can define the abstraction it needs:

public interface IProductRepository
{
    Task<Product?> GetByIdAsync(
        int id,
        CancellationToken cancellationToken);

    Task SaveChangesAsync(
        CancellationToken cancellationToken);
}

Application knows the capability.

It does not know whether that capability is implemented using EF Core, Dapper, SQL Server or another persistence technology.

10. Do We Need a Repository for Every Table?

No.

A common Clean Architecture mistake is mechanically creating:

IRepository<Product>
IRepository<Order>
IRepository<Customer>
IRepository<Category>
IRepository<Everything>

Entity Framework Core's DbContext already provides many repository and Unit of Work characteristics.

Introduce repository abstractions when they provide a meaningful architectural boundary, not merely because a diagram says that Clean Architecture should contain repositories.

11. The CreateOrder Use Case

Command:

public sealed record CreateOrderCommand(
    int ProductId,
    int Quantity);

Result:

public sealed record CreateOrderResult(
    long OrderId,
    decimal TotalAmount);

Handler:

public sealed class CreateOrderHandler
{
    private readonly IProductRepository
        _productRepository;

    private readonly IOrderRepository
        _orderRepository;

    private readonly IUnitOfWork
        _unitOfWork;

    public CreateOrderHandler(
        IProductRepository productRepository,
        IOrderRepository orderRepository,
        IUnitOfWork unitOfWork)
    {
        _productRepository =
            productRepository;

        _orderRepository =
            orderRepository;

        _unitOfWork =
            unitOfWork;
    }

    public async Task<CreateOrderResult> HandleAsync(
        CreateOrderCommand command,
        CancellationToken cancellationToken)
    {
        var product =
            await _productRepository
                .GetByIdAsync(
                    command.ProductId,
                    cancellationToken);

        if (product is null)
            throw new ProductNotFoundException(
                command.ProductId);

        product.DecreaseStock(
            command.Quantity);

        var order =
            new Order(
                product.Id,
                command.Quantity,
                product.Price);

        _orderRepository.Add(order);

        await _unitOfWork.SaveChangesAsync(
            cancellationToken);

        return new CreateOrderResult(
            order.Id,
            order.TotalAmount);
    }
}

The Application layer controls the business workflow, while infrastructure details remain hidden behind abstractions.

12. The Infrastructure Layer

Infrastructure contains technical implementations required by the inner layers.

Typical examples include:

  • Entity Framework Core
  • SQL Server
  • Repository implementations
  • Email delivery
  • File storage
  • Message brokers
  • Redis
  • External HTTP APIs

13. DbContext in Infrastructure

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

    public DbSet<Product> Products =>
        Set<Product>();

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

    protected override void OnModelCreating(
        ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(
            typeof(ShopDbContext).Assembly);
    }
}

Persistence configuration can remain outside the Domain model.

14. Fluent Entity Configuration

public sealed class ProductConfiguration
    : IEntityTypeConfiguration<Product>
{
    public void Configure(
        EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Products");

        builder.HasKey(x => x.Id);

        builder.Property(x => x.Name)
            .HasMaxLength(200)
            .IsRequired();

        builder.Property(x => x.Price)
            .HasPrecision(18, 2);

        builder.Property(x => x.StockQuantity)
            .IsRequired();
    }
}

The Domain project therefore does not need a dependency on Entity Framework Core attributes or types.

15. Repository Implementation

public sealed class ProductRepository
    : IProductRepository
{
    private readonly ShopDbContext _db;

    public ProductRepository(
        ShopDbContext db)
    {
        _db = db;
    }

    public Task<Product?> GetByIdAsync(
        int id,
        CancellationToken cancellationToken)
    {
        return _db.Products
            .FirstOrDefaultAsync(
                x => x.Id == id,
                cancellationToken);
    }
}

Infrastructure depends on the interface owned by the inner layer, not the other way around.

16. Unit of Work

When multiple repositories share the same DbContext, a use case may need a single commit boundary.

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

Implementation:

public sealed class EfUnitOfWork
    : IUnitOfWork
{
    private readonly ShopDbContext _db;

    public EfUnitOfWork(
        ShopDbContext db)
    {
        _db = db;
    }

    public Task<int> SaveChangesAsync(
        CancellationToken cancellationToken)
    {
        return _db.SaveChangesAsync(
            cancellationToken);
    }
}

Because DbContext already provides Unit of Work behavior, this abstraction should be added only when it provides real value.

17. Infrastructure Dependency Injection

public static class DependencyInjection
{
    public static IServiceCollection
        AddInfrastructure(
            this IServiceCollection services,
            IConfiguration configuration)
    {
        services.AddDbContext<ShopDbContext>(
            options =>
                options.UseSqlServer(
                    configuration
                        .GetConnectionString(
                            "DefaultConnection")));

        services.AddScoped<
            IProductRepository,
            ProductRepository>();

        services.AddScoped<
            IOrderRepository,
            OrderRepository>();

        services.AddScoped<
            IUnitOfWork,
            EfUnitOfWork>();

        return services;
    }
}

18. The API Layer

The API layer is responsible for communication with the outside world.

HTTP-specific concerns belong here:

  • Controllers
  • Request and response models
  • Authentication
  • Authorization
  • Middleware
  • ProblemDetails

The API layer should not become the primary home of business rules.

19. Thin Controllers

[ApiController]
[Route("api/orders")]
public sealed class OrdersController
    : ControllerBase
{
    private readonly CreateOrderHandler
        _handler;

    public OrdersController(
        CreateOrderHandler handler)
    {
        _handler = handler;
    }

    [HttpPost]
    public async Task<IActionResult> Create(
        CreateOrderRequest request,
        CancellationToken cancellationToken)
    {
        var result =
            await _handler.HandleAsync(
                new CreateOrderCommand(
                    request.ProductId,
                    request.Quantity),
                cancellationToken);

        return CreatedAtAction(
            nameof(GetById),
            new { id = result.OrderId },
            result);
    }

    [HttpGet("{id:long}")]
    public IActionResult GetById(long id)
    {
        return Ok();
    }
}

The controller should mainly translate:

HTTP Request
      ↓
Application Use Case
      ↓
HTTP Response

20. Program.cs as the Composition Root

Concrete implementations have to be connected somewhere.

In ASP.NET Core, that place is usually Program.cs:

var builder =
    WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddScoped<
    CreateOrderHandler>();

builder.Services.AddInfrastructure(
    builder.Configuration);

var app = builder.Build();

app.UseExceptionHandler();

app.MapControllers();

app.Run();

The API project may reference Infrastructure so that the composition root can register concrete implementations.

The important restriction is that normal API/application code should avoid directly depending on Infrastructure implementation types.

21. Real Problem: Controller Uses DbContext Directly

OrdersController
      ↓
ShopDbContext
      ↓
SQL Server

This may be acceptable for very simple CRUD endpoints.

But when business behavior grows:

  • Controllers become difficult to test.
  • HTTP concerns and business rules become mixed.
  • The use case becomes difficult to reuse from another entry point.

An Application use case can instead be called from REST, a background worker or a message consumer.

22. Infrastructure Details Leaking Through Interfaces

Consider:

public interface IOrderService
{
    IQueryable<OrderEntity>
        GetOrders();
}

Even if this interface exists in Application, it exposes persistence behavior to its consumers.

A stronger boundary might expose the actual use case:

public interface IOrderQueryService
{
    Task<IReadOnlyList<OrderListItem>>
        GetCustomerOrdersAsync(
            int customerId,
            CancellationToken cancellationToken);
}

23. DTOs Are Not Domain Entities

Returning Domain entities directly from API endpoints tightly couples the public API contract to the Domain model.

Use a response model when that boundary matters:

public sealed record OrderResponse(
    long Id,
    int ProductId,
    int Quantity,
    decimal TotalAmount,
    string Status);

The public API and Domain model can now evolve more independently.

24. Where Does Validation Belong?

Not every validation rule belongs to the same layer.

Request Validation

Examples include required fields, string lengths and syntactic input validation.

Domain Invariants

Examples include:

Stock cannot become negative.
A cancelled order cannot be shipped.
A completed payment cannot be completed again.

Domain invariants should remain protected by the Domain even when input validation also exists at the API boundary.

25. Domain Exceptions and HTTP Errors

Domain can express the business failure:

public sealed class
    InsufficientStockException
    : DomainException
{
    public InsufficientStockException()
        : base(
            "Requested quantity exceeds stock.")
    {
    }
}

The API layer can translate it to HTTP 409.

The Domain should not know what HTTP 409 means. HTTP is an outer-layer concern.

26. External-Service Integrations

Application can define the capability it needs:

public interface IPaymentGateway
{
    Task<PaymentResult> ChargeAsync(
        PaymentRequest request,
        CancellationToken cancellationToken);
}

Infrastructure provides the implementation:

public sealed class PaymentGateway
    : IPaymentGateway
{
    private readonly HttpClient _httpClient;

    public PaymentGateway(
        HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<PaymentResult>
        ChargeAsync(
            PaymentRequest request,
            CancellationToken cancellationToken)
    {
        // Provider-specific implementation.

        return PaymentResult.Success();
    }
}

Application depends on a payment capability, not a specific provider implementation.

27. Is Swapping Providers Really the Main Benefit?

Not really.

Clean Architecture presentations often make it sound as if every application replaces SQL Server with PostgreSQL before lunch and switches payment providers after dinner. Real projects tend to be less theatrical.

The more practical benefits are:

  • Business logic is easier to test.
  • Technical changes have a smaller blast radius.
  • Use cases can be reused from different entry points.
  • The codebase is easier to reason about as it grows.

28. Domain Events

Important Domain behavior can produce Domain Events:

public sealed record OrderCreatedDomainEvent(
    long OrderId);

Handlers outside the core entity can then perform secondary actions such as:

  • Creating an Outbox event
  • Writing an audit record
  • Starting another application workflow

Domain Events are useful for meaningful business events, not for turning every property assignment into a miniature event-driven ecosystem.

29. Clean Architecture Is Not CQRS

CQRS, handlers and MediatR are frequently used in Clean Architecture projects.

They are optional.

This is still perfectly valid:

Controller
    ↓
Application Service
    ↓
Domain
    ↓
Repository Abstraction

Using MediatR does not automatically make an architecture clean, and not using it does not make an architecture unclean.

30. Read Models Do Not Need to Use the Domain Model

Complex reporting queries may benefit from direct projections using EF Core or Dapper.

A dashboard query does not necessarily need to instantiate full aggregates simply to display five columns.

Application can expose a query abstraction and Infrastructure can provide an optimized implementation.

Clean Architecture should protect boundaries without sacrificing performance for ceremony.

31. Unit Testing the Domain

[Fact]
public void DecreaseStock_ShouldReduceStock()
{
    var product =
        new Product(
            "Keyboard",
            1000,
            10);

    product.DecreaseStock(3);

    Assert.Equal(
        7,
        product.StockQuantity);
}

No database or ASP.NET Core host is required.

The Domain is ordinary C#, which keeps these tests fast.

32. Testing Application Use Cases

Application use cases can use fake or mocked abstractions:

Fake ProductRepository
        ↓
CreateOrderHandler
        ↓
Domain
        ↓
Fake OrderRepository

Infrastructure implementations can then be tested separately with real integration tests.

33. Integration Testing the Entire Flow

HttpClient
    ↓
API
    ↓
Application
    ↓
Infrastructure
    ↓
EF Core
    ↓
SQL Server

Clean boundaries make it easier to choose the appropriate testing level for each type of risk.

34. Do Not Put Infrastructure Inside Domain Entities

A Domain entity should not contain code like:

public async Task SendEmailAsync()
{
    using var smtp =
        new SmtpClient(...);

    await smtp.SendMailAsync(...);
}

The Domain can express that an Order was created.

Whether that event becomes an email, push notification or broker message is an outer-layer decision.

35. Circular Dependencies Are a Warning Sign

Application
    ↓
Infrastructure
    ↓
Application

If projects require circular references, an abstraction may have been defined in the wrong layer.

Moving the abstraction toward the higher-level policy that needs it often restores the correct dependency direction.

36. Where Should Transactions Be Managed?

Transactions are technically implemented by Infrastructure, but the business use case defines what needs to be atomic.

Create Order
    │
    ├── Decrease inventory
    ├── Create Order
    └── Create Outbox event

Application can define the transaction boundary through a Unit of Work abstraction, while Infrastructure implements it with EF Core.

37. More Layers Are Not Automatically Better

A poorly applied architecture may become:

Controller
 ↓
Service
 ↓
Manager
 ↓
Handler
 ↓
Processor
 ↓
Repository
 ↓
GenericRepository
 ↓
UnitOfWork
 ↓
DbContext

If every class simply forwards the call to the next class, the architecture hasn't reduced complexity. It has merely distributed it across more files.

An abstraction is valuable when it hides meaningful variability, improves testability or creates a real architectural boundary.

38. Does Every CRUD Application Need Clean Architecture?

No.

A simple administration application with a few tables may not benefit from four projects, dozens of interfaces and a large CQRS pipeline.

Clean Architecture becomes more valuable when:

  • The business domain is complex.
  • The application will evolve for years.
  • Multiple developers work on the codebase.
  • There are several infrastructure integrations.
  • Automated testing is important.
  • The system is expected to grow.

39. Clean Architecture Does Not Mean Microservices

A Clean Architecture application can still be a monolith deployed as one process.

CleanShop.Api
    │
    ├── Domain
    ├── Application
    └── Infrastructure

One application
One deployment
Potentially one database

A well-structured modular monolith is often easier to maintain than prematurely splitting the system into network-distributed services.

40. The Real Benefit of Clean Architecture

Imagine that CreateOrder initially runs from a REST API:

REST API
   ↓
CreateOrderHandler
   ↓
Domain

Later, a message consumer needs the same use case:

Message Consumer
       ↓
Application Use Case
       ↓
Domain

And later a background process does too:

BackgroundService
       ↓
Application Use Case
       ↓
Domain

Because the business logic was not embedded inside an HTTP controller, the same use case can serve multiple entry points.

41. Recommended Dependency Structure

                  ┌──────────────┐
                  │     API      │
                  │ Controllers  │
                  │ Middleware   │
                  └──────┬───────┘
                         │
                         ▼
                  ┌──────────────┐
                  │ Application  │
                  │ Use Cases    │
                  │ Interfaces   │
                  │ DTOs         │
                  └──────┬───────┘
                         │
                         ▼
                  ┌──────────────┐
                  │    Domain    │
                  │ Entities     │
                  │ ValueObjects │
                  │ Rules        │
                  └──────────────┘

                  ▲
                  │ implements
                  │
            ┌─────┴──────────┐
            │ Infrastructure │
            │ EF Core        │
            │ SQL Server     │
            │ HTTP Clients   │
            │ Messaging      │
            └────────────────┘

42. Common Clean Architecture Mistakes

Creating interfaces for everything

Not every concrete class needs an interface. Interfaces should represent useful boundaries or abstractions.

Treating Domain as merely an Entities folder

Moving classes into Domain does not help if all business behavior still lives in controllers and procedural services.

Using Generic Repository everywhere

Reimplementing DbContext behind layers of generic abstractions can create more complexity than value.

Leaking EF Core into Application

Application code that depends on DbContext, DbSet or provider-specific query behavior weakens the architectural boundary.

Confusing CQRS with Clean Architecture

CQRS can complement Clean Architecture, but it is not a requirement.

Applying the same architecture to every project

A tiny CRUD system may not justify the additional abstraction cost.

43. Conclusion

Clean Architecture with ASP.NET Core is not about creating projects named Domain, Application and Infrastructure simply because an architecture diagram says so.

Its real purpose is to protect business rules from technical implementation details.

In a well-structured application:

  • Domain owns business rules.
  • Application coordinates use cases.
  • Infrastructure implements technical capabilities.
  • API manages communication with the outside world.

Dependencies point toward the business core.

Technologies such as SQL Server, EF Core, HTTP, SMTP and message brokers stay near the outside of the architecture rather than becoming the foundation of the business model.

The result is business logic that is:

  • Easier to unit test.
  • Less coupled to HTTP.
  • Less affected by infrastructure changes.
  • Easier to understand and maintain.

Clean Architecture is still a tool, not a goal.

Adding interfaces everywhere, introducing five classes for every operation or forcing CQRS into every project does not automatically make code cleaner.

The right question is not:

“How many layers do we have?”

The better question is:

“How independent are our business rules from technical details, and how well can we contain the impact of change?”

If an ASP.NET Core application has a good answer to that question, it is already achieving the most important goal of Clean Architecture.

```
//

0 Comments

Write Comment

E-Mail address will not be published