EF Core Performance Optimization :👈 👉:ASP.NET Core Dependency Injection

Clean Architecture in ASP.NET Core

Clean Architecture in ASP.NET Core

1. Introduction

Clean Architecture is a software architectural approach that organizes an application into independent layers, keeping business logic separate from infrastructure, frameworks, databases, and user interfaces.

The primary goal is to make an application:

  • Maintainable and easy to understand.
  • Testable without depending on external systems.
  • Independent of databases and frameworks.
  • Flexible enough to accommodate future changes.
  • Easier to extend as business requirements grow.

In a typical ASP.NET Core application, controllers, business logic, database operations, and external service integrations can become tightly coupled. Clean Architecture helps separate these responsibilities.

Example: Consider an e-commerce application that manages customers, products, orders, and payments.

Instead of putting all the logic inside controllers or directly accessing Entity Framework Core from every controller, Clean Architecture separates the application into different projects with clearly defined responsibilities.

2. Table of Contents

  1. Why Clean Architecture Is Required
  2. Clean Architecture Overview
  3. The Dependency Rule
  4. Four Main Layers
  5. Domain Layer
  6. Application Layer
  7. Infrastructure Layer
  8. Presentation Layer
  9. ASP.NET Core Project Structure
  10. Implement Clean Architecture Step by Step
  11. Dependency Injection
  12. CQRS and MediatR
  13. Validation
  14. Exception Handling
  15. Testing Clean Architecture
  16. Advantages and Disadvantages
  17. Common Mistakes
  18. Best Practices
  19. Clean Architecture vs Other Architectures
  20. Interview Questions and Answers
  21. Summary

3. Why Clean Architecture Is Required

Consider a traditional ASP.NET Core application with the following structure:

Controllers
    |
    v
Entity Framework Core
    |
    v
SQL Server

Here, the controller directly accesses Entity Framework Core and performs business operations.

As the application grows, several problems can arise:

  • Controllers contain too much business logic.
  • Database operations are tightly coupled with application behavior.
  • Business logic becomes difficult to test independently.
  • Changing the database can affect multiple application components.
  • External service integrations become difficult to replace.
  • Code duplication increases across controllers.

Without Clean Architecture

ProductsController Business Logic Validation EF Core Queries External Payment API SQL Server

Without Clean Architecture: Controller directly depends on business logic, validation, data access, database, and external services

The controller is responsible for too many things.

With Clean Architecture

Presentation Layer Application Layer Domain Layer Infrastructure SQL Server Entity Framework Core External APIs Implements Application Interfaces

Each layer has a specific responsibility, making the application easier to maintain and test.

4. Clean Architecture Overview

Clean Architecture generally consists of four main layers:

  1. Domain Layer: Contains core business entities and business rules.
  2. Application Layer: Contains application use cases, interfaces, commands, queries, and business workflows.
  3. Infrastructure Layer: Contains technical implementations such as database access, external APIs, file storage, and messaging.
  4. Presentation Layer: Exposes the application through ASP.NET Core Web APIs, controllers, or other user interfaces.

Architecture Diagram

PRESENTATION LAYER ASP.NET Core Web API / Controllers APPLICATION LAYER Use Cases / Services / CQRS / DTOs Interfaces / Validation / Behaviors DOMAIN LAYER Entities / Value Objects / Domain Rules Domain Events / Domain Services INFRASTRUCTURE LAYER EF Core / SQL Server / External APIs Repository Implementations / Email

Infrastructure implements interfaces defined by the Application or Domain layer.

Important: The diagram shows logical responsibilities, not every project reference. The key principle is that the Domain layer does not depend on the Application, Infrastructure, or Presentation layers. The Application layer does not depend on Infrastructure or Presentation.

5. The Dependency Rule

The Dependency Rule is the most important principle of Clean Architecture.

Dependencies should point inward, toward the business logic.

Outer layers can depend on inner layers, but inner layers should not depend on outer layers.

Valid Dependencies

Presentation  ---------> Application
Infrastructure --------> Application
Application   ---------> Domain
Domain        ---------> No outer layer

Invalid Dependencies

Domain ---------> Entity Framework Core
Domain ---------> ASP.NET Core
Application ---> SQL Server implementation
Application ---> Web API Controller

These dependencies violate the Dependency Rule because the core business logic becomes dependent on implementation details.

Example

Suppose an application needs to retrieve products from a database.

A poor design is to directly use Entity Framework Core inside the Application layer:

public class ProductService
{
    private readonly AppDbContext _context;
    public ProductService(AppDbContext context)
    {
        _context = context;
    }
    public async Task<List<Product>> GetProducts()
    {
        return await _context.Products.ToListAsync();
    }
}

The Application layer now depends directly on Entity Framework Core.

A better approach is to define an abstraction in the Application layer and implement it in Infrastructure.

public interface IProductRepository
{
    Task<List<Product>> GetAllAsync();
}

The Infrastructure layer provides the implementation:

public class ProductRepository : IProductRepository
{
    private readonly AppDbContext _context;
    public ProductRepository(AppDbContext context)
    {
        _context = context;
    }
    public async Task<List<Product>> GetAllAsync()
    {
        return await _context.Products.ToListAsync();
    }
}

The Application layer depends on the interface, not the database implementation.

6. Four Main Layers

Layer Responsibility Examples
Domain Core business rules Entities, Value Objects, Domain Events
Application Application use cases Services, Commands, Queries, DTOs
Infrastructure External technical implementations EF Core, SQL Server, Email, File Storage
Presentation Application entry points Controllers, Middleware, HTTP Endpoints

7. Domain Layer

The Domain layer is the core of the application.

It contains the most important business concepts and rules. It should not depend on any external framework or infrastructure implementation.

What Does the Domain Layer Contain?

  • Entities.
  • Value Objects.
  • Domain Services.
  • Domain Events.
  • Business Rules.
  • Domain Exceptions.

7.1 Entities

An Entity is an object that has a unique identity and represents an important business concept.

Example: Product.

namespace MyApp.Domain.Entities;
public class Product
{
    public int Id { get; private set; }
    public string Name { get; private set; }
    public decimal Price { get; private set; }
    public Product(string name, decimal price)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("Product name is required.");
        if (price <= 0)
            throw new ArgumentException("Price must be greater than zero.");
        Name = name;
        Price = price;
    }
    public void UpdatePrice(decimal newPrice)
    {
        if (newPrice <= 0)
            throw new ArgumentException("Price must be greater than zero.");
        Price = newPrice;
    }
}

Explanation:

  • Product represents a business entity.
  • Id identifies the product.
  • The constructor validates the initial product data.
  • UpdatePrice() protects the business rule that a product price must be positive.
  • Private setters prevent unrestricted modification from outside the entity.

7.2 Value Objects

A Value Object represents a concept defined by its values rather than by a unique identity.

Example: Money.

namespace MyApp.Domain.ValueObjects;
public record Money(decimal Amount, string Currency)
{
    public Money
    {
        if (Amount < 0)
            throw new ArgumentException("Amount cannot be negative.");
        if (string.IsNullOrWhiteSpace(Currency))
            throw new ArgumentException("Currency is required.");
    }
}

A Value Object is generally immutable. Two Value Objects with the same values are considered equivalent.

Note: The compact validation syntax shown above is illustrative and depends on the C# language version. A conventional constructor or factory method can be used when that syntax is unavailable.

7.3 Domain Services

A Domain Service contains business logic that does not naturally belong to a single entity or Value Object.

Example: Product pricing calculation based on a business rule.

namespace MyApp.Domain.Services;
public class PricingService
{
    public decimal CalculateDiscount(
        decimal price,
        decimal discountPercentage)
    {
        if (price < 0)
            throw new ArgumentException("Price cannot be negative.");
        if (discountPercentage < 0 ||
            discountPercentage > 100)
            throw new ArgumentException("Invalid discount percentage.");
        return price * discountPercentage / 100;
    }
}

Domain Services should contain domain-related rules, not database access or HTTP operations.

7.4 Domain Events

A Domain Event represents something important that has happened in the business domain.

Examples:

  • OrderPlaced.
  • PaymentCompleted.
  • ProductCreated.
  • CustomerRegistered.

Domain Events allow different parts of the application to react to business events without tightly coupling the entities to those components.

8. Application Layer

The Application layer contains the use cases of the system.

It coordinates the execution of business operations by interacting with Domain entities and abstractions for external dependencies.

What Does the Application Layer Contain?

  • Application Services.
  • Commands and Queries.
  • DTOs.
  • Repository Interfaces.
  • Validation Rules.
  • Application Interfaces.
  • Application Exceptions.

8.1 DTOs

DTO stands for Data Transfer Object.

DTOs transfer data between application boundaries without exposing internal Domain entities directly.

Example:

namespace MyApp.Application.DTOs;
public class ProductDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Why use DTOs?

  • Prevent exposing internal Domain entities directly.
  • Control which properties are returned to clients.
  • Keep API contracts independent of database models.
  • Support different request and response structures for different use cases.

8.2 Repository Interfaces

The Application layer defines abstractions required by its use cases.

namespace MyApp.Application.Interfaces;
using MyApp.Domain.Entities;
public interface IProductRepository
{
    Task<Product?> GetByIdAsync(int id);
    Task<List<Product>> GetAllAsync();
    Task AddAsync(Product product);
    Task SaveChangesAsync();
}

The interface defines what the application needs without specifying how the data is stored.

8.3 Application Service

An Application Service coordinates a use case.

Example: Retrieve a product by its ID.

using MyApp.Application.DTOs;
using MyApp.Application.Interfaces;
namespace MyApp.Application.Services;
public class ProductService
{
    private readonly IProductRepository _repository;
    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }
    public async Task<ProductDto?> GetProductByIdAsync(int id)
    {
        var product = await _repository.GetByIdAsync(id);
        if (product == null)
            return null;
        return new ProductDto
        {
            Id = product.Id,
            Name = product.Name,
            Price = product.Price
        };
    }
}

The Application Service:

  • Uses the repository abstraction.
  • Coordinates the use case.
  • Maps the Domain entity to a DTO.
  • Does not know whether data comes from SQL Server, PostgreSQL, or another source.

9. Infrastructure Layer

The Infrastructure layer contains implementations of external technical dependencies.

What Does the Infrastructure Layer Contain?

  • Entity Framework Core.
  • Database Contexts.
  • Repository Implementations.
  • SQL Server or PostgreSQL integration.
  • External API integrations.
  • Email Services.
  • File Storage.
  • Message Brokers.
  • Caching Implementations.

9.1 Entity Framework Core DbContext

The Infrastructure layer contains the database context.

using Microsoft.EntityFrameworkCore;
using MyApp.Domain.Entities;
namespace MyApp.Infrastructure.Persistence;
public class AppDbContext : DbContext
{
    public AppDbContext(
        DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
    public DbSet<Product> Products => Set<Product>();
}

9.2 Repository Implementation

The Infrastructure layer implements the repository interface defined in the Application layer.

using Microsoft.EntityFrameworkCore;
using MyApp.Application.Interfaces;
using MyApp.Domain.Entities;
using MyApp.Infrastructure.Persistence;
namespace MyApp.Infrastructure.Repositories;
public class ProductRepository : IProductRepository
{
    private readonly AppDbContext _context;
    public ProductRepository(AppDbContext context)
    {
        _context = context;
    }
    public async Task<Product?> GetByIdAsync(int id)
    {
        return await _context.Products
            .FirstOrDefaultAsync(p => p.Id == id);
    }
    public async Task<List<Product>> GetAllAsync()
    {
        return await _context.Products.ToListAsync();
    }
    public async Task AddAsync(Product product)
    {
        await _context.Products.AddAsync(product);
    }
    public async Task SaveChangesAsync()
    {
        await _context.SaveChangesAsync();
    }
}

Important: The Infrastructure layer depends on the Application and Domain layers to implement their abstractions. The Application layer does not reference the Infrastructure project.

10. Presentation Layer

The Presentation layer exposes application functionality to external consumers.

In an ASP.NET Core Web API, this layer generally contains:

  • Controllers.
  • HTTP endpoints.
  • Request and response handling.
  • Authentication and authorization configuration.
  • Middleware configuration.
  • Dependency injection composition.

10.1 API Controller

The controller receives HTTP requests and delegates the actual use case to the Application layer.

using Microsoft.AspNetCore.Mvc;
using MyApp.Application.Services;
namespace MyApp.Api.Controllers;
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    private readonly ProductService _service;
    public ProductsController(ProductService service)
    {
        _service = service;
    }
    [HttpGet("{id}")]
    public async Task<IActionResult> Get(int id)
    {
        var product = await _service.GetProductByIdAsync(id);
        if (product == null)
            return NotFound();
        return Ok(product);
    }
}

The controller does not directly access Entity Framework Core or contain the product retrieval business workflow.

11. ASP.NET Core Project Structure

A typical Clean Architecture solution can be organized into four projects.

MyApp.sln
|
+-- MyApp.Domain
|   |
|   +-- Entities
|   |   +-- Product.cs
|   |
|   +-- ValueObjects
|   |   +-- Money.cs
|   |
|   +-- Services
|   |   +-- PricingService.cs
|   |
|   +-- Events
|
+-- MyApp.Application
|   |
|   +-- DTOs
|   |   +-- ProductDto.cs
|   |
|   +-- Interfaces
|   |   +-- IProductRepository.cs
|   |
|   +-- Services
|   |   +-- ProductService.cs
|   |
|   +-- Features
|   +-- Validators
|
+-- MyApp.Infrastructure
|   |
|   +-- Persistence
|   |   +-- AppDbContext.cs
|   |
|   +-- Repositories
|   |   +-- ProductRepository.cs
|   |
|   +-- ExternalServices
|   +-- DependencyInjection.cs
|
+-- MyApp.Api
    |
    +-- Controllers
    |   +-- ProductsController.cs
    |
    +-- Middleware
    +-- Program.cs

Project Reference Structure

MyApp.Domain
    |
    | No project dependencies
    |
    v
MyApp.Application
    |
    +----> MyApp.Domain
MyApp.Infrastructure
    |
    +----> MyApp.Application
    |
    +----> MyApp.Domain
MyApp.Api
    |
    +----> MyApp.Application
    |
    +----> MyApp.Infrastructure

The API project acts as the composition root. It connects the application abstractions to their Infrastructure implementations through dependency injection.

12. Implement Clean Architecture Step by Step

Consider building a Product Management API using ASP.NET Core, Entity Framework Core, and SQL Server.

Step 1: Create the Solution

dotnet new sln -n MyApp
dotnet new classlib -n MyApp.Domain
dotnet new classlib -n MyApp.Application
dotnet new classlib -n MyApp.Infrastructure
dotnet new webapi -n MyApp.Api

Step 2: Add Projects to the Solution

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

Step 3: Add Project References

Application depends on Domain:

dotnet add MyApp.Application reference MyApp.Domain

Infrastructure depends on Application and Domain:

dotnet add MyApp.Infrastructure reference MyApp.Application
dotnet add MyApp.Infrastructure reference MyApp.Domain

API depends on Application and Infrastructure:

dotnet add MyApp.Api reference MyApp.Application
dotnet add MyApp.Api reference MyApp.Infrastructure

Step 4: Install Entity Framework Core Packages

Install the SQL Server provider and EF Core design package in the Infrastructure project.

dotnet add MyApp.Infrastructure package Microsoft.EntityFrameworkCore.SqlServer
dotnet add MyApp.Infrastructure package Microsoft.EntityFrameworkCore.Design

Step 5: Create the Domain Entity

public class Product
{
    public int Id { get; private set; }
    public string Name { get; private set; }
    public decimal Price { get; private set; }
    public Product(string name, decimal price)
    {
        if (string.IsNullOrWhiteSpace(name))
            throw new ArgumentException("Name is required.");
        if (price <= 0)
            throw new ArgumentException("Price must be positive.");
        Name = name;
        Price = price;
    }
}

Step 6: Create the Repository Interface

public interface IProductRepository
{
    Task<Product?> GetByIdAsync(int id);
    Task<List<Product>> GetAllAsync();
    Task AddAsync(Product product);
    Task SaveChangesAsync();
}

Step 7: Create the Database Context

public class AppDbContext : DbContext
{
    public AppDbContext(
        DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
    public DbSet<Product> Products => Set<Product>();
}

Step 8: Implement the Repository

public class ProductRepository : IProductRepository
{
    private readonly AppDbContext _context;
    public ProductRepository(AppDbContext context)
    {
        _context = context;
    }
    public async Task<Product?> GetByIdAsync(int id)
    {
        return await _context.Products
            .FirstOrDefaultAsync(x => x.Id == id);
    }
    public async Task<List<Product>> GetAllAsync()
    {
        return await _context.Products.ToListAsync();
    }
    public async Task AddAsync(Product product)
    {
        await _context.Products.AddAsync(product);
    }
    public async Task SaveChangesAsync()
    {
        await _context.SaveChangesAsync();
    }
}

Step 9: Create the Application Service

public class ProductService
{
    private readonly IProductRepository _repository;
    public ProductService(IProductRepository repository)
    {
        _repository = repository;
    }
    public async Task<Product?> GetByIdAsync(int id)
    {
        return await _repository.GetByIdAsync(id);
    }
    public async Task CreateAsync(string name, decimal price)
    {
        var product = new Product(name, price);
        await _repository.AddAsync(product);
        await _repository.SaveChangesAsync();
    }
}

Step 10: Register Dependencies

Register the services in the API project's Program.cs:

using Microsoft.EntityFrameworkCore;
using MyApp.Application.Interfaces;
using MyApp.Application.Services;
using MyApp.Infrastructure.Persistence;
using MyApp.Infrastructure.Repositories;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<ProductService>();
var app = builder.Build();
app.MapControllers();
app.Run();

Step 11: Configure the Connection String

In the API project's appsettings.json:

{
    "ConnectionStrings": {
        "DefaultConnection": "Server=.;Database=MyAppDb;Trusted_Connection=True;TrustServerCertificate=True"
    }
}

Use appropriate secret management and secure connection settings in production rather than storing sensitive credentials in source-controlled configuration files.

Step 12: Create the Database

Run Entity Framework Core migrations with the Infrastructure project as the migration assembly and the API project as the startup project.

dotnet ef migrations add InitialCreate \
    --project MyApp.Infrastructure \
    --startup-project MyApp.Api
dotnet ef database update \
    --project MyApp.Infrastructure \
    --startup-project MyApp.Api

The application can now expose product endpoints through the API controller.

13. Dependency Injection in Clean Architecture

Dependency Injection (DI) is used to provide the required dependencies to classes rather than allowing them to create their own dependencies.

In Clean Architecture, the Application layer defines interfaces and the Infrastructure layer provides their implementations.

Example

Application interface:

public interface IEmailService
{
    Task SendEmailAsync(string to, string subject, string body);
}

Infrastructure implementation:

public class EmailService : IEmailService
{
    public async Task SendEmailAsync(
        string to,
        string subject,
        string body)
    {
        // Integrate with an email provider.
        await Task.CompletedTask;
    }
}

Registration:

builder.Services.AddScoped<IEmailService, EmailService>();

Application service:

public class NotificationService
{
    private readonly IEmailService _emailService;
    public NotificationService(IEmailService emailService)
    {
        _emailService = emailService;
    }
    public async Task NotifyAsync(string email)
    {
        await _emailService.SendEmailAsync(
            email,
            "Welcome",
            "Welcome to our application.");
    }
}

The Application layer depends on the interface. It does not know which email provider is used.

Common DI Lifetimes

Lifetime Behavior Typical Usage
Transient A new instance is created each time it is requested. Lightweight stateless services.
Scoped One instance is created per request scope. DbContext and request-level services.
Singleton One instance is shared throughout the application's lifetime. Thread-safe shared services and configuration providers.

14. CQRS and MediatR in Clean Architecture

CQRS stands for Command Query Responsibility Segregation.

It separates operations that change data from operations that retrieve data.

  • Command: Performs an operation that changes application state.
  • Query: Retrieves data without changing application state.

MediatR is a library commonly used to implement the mediator pattern in .NET applications. It can dispatch commands and queries to their respective handlers.

Example: Create Product Command

using MediatR;
public record CreateProductCommand(
    string Name,
    decimal Price
) : IRequest<int>;

Command Handler

using MediatR;
using MyApp.Application.Interfaces;
using MyApp.Domain.Entities;
public class CreateProductHandler
    : IRequestHandler<CreateProductCommand, int>
{
    private readonly IProductRepository _repository;
    public CreateProductHandler(IProductRepository repository)
    {
        _repository = repository;
    }
    public async Task<int> Handle(
        CreateProductCommand request,
        CancellationToken cancellationToken)
    {
        var product = new Product(
            request.Name,
            request.Price);
        await _repository.AddAsync(product);
        await _repository.SaveChangesAsync();
        return product.Id;
    }
}

Controller Using MediatR

using MediatR;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
    private readonly ISender _sender;
    public ProductsController(ISender sender)
    {
        _sender = sender;
    }
    [HttpPost]
    public async Task<IActionResult> Create(
        CreateProductCommand command)
    {
        var id = await _sender.Send(command);
        return CreatedAtAction(
            nameof(GetById),
            new { id },
            new { id });
    }
    [HttpGet("{id}")]
    public IActionResult GetById(int id)
    {
        return Ok();
    }
}

Why use CQRS and MediatR?

  • Separates commands and queries.
  • Organizes application operations into individual handlers.
  • Reduces direct dependencies between controllers and application services.
  • Supports pipeline behaviors for validation, logging, and other cross-cutting concerns.

Important: CQRS and MediatR are optional. Clean Architecture does not require them. For a small application, straightforward application services may be simpler.

15. Validation in Clean Architecture

Validation ensures that incoming data satisfies the application's requirements before the use case is executed.

For example, a product should have a valid name and a positive price.

Example Using FluentValidation

Install FluentValidation:

dotnet add package FluentValidation

Create a validator:

using FluentValidation;
public class CreateProductCommandValidator
    : AbstractValidator<CreateProductCommand>
{
    public CreateProductCommandValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty()
            .MaximumLength(100);
        RuleFor(x => x.Price)
            .GreaterThan(0);
    }
}

Validation responsibilities can exist at different levels:

  • Presentation validation: Checks HTTP request structure and basic input requirements.
  • Application validation: Checks whether a use case request is valid.
  • Domain validation: Protects essential business invariants that must always remain true.

For example, checking whether a required field is present can happen at the request boundary, while ensuring a product price is positive should also be protected by the Domain entity.

16. Exception Handling

Exception handling is used to manage unexpected errors and provide consistent error responses to API clients.

Clean Architecture should avoid mixing HTTP-specific error handling into the Domain layer.

For example:

  • The Domain layer can throw a business rule exception.
  • The Application layer can propagate or translate application errors.
  • The Presentation layer can convert exceptions into appropriate HTTP responses.

Example: Global Exception Handler

using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
public class GlobalExceptionHandler : IExceptionHandler
{
    private readonly ILogger<GlobalExceptionHandler> _logger;
    public GlobalExceptionHandler(
        ILogger<GlobalExceptionHandler> logger)
    {
        _logger = logger;
    }
    public async ValueTask<bool> TryHandleAsync(
        HttpContext httpContext,
        Exception exception,
        CancellationToken cancellationToken)
    {
        _logger.LogError(
            exception,
            "An unexpected error occurred.");
        httpContext.Response.StatusCode =
            StatusCodes.Status500InternalServerError;
        await httpContext.Response.WriteAsJsonAsync(
            new ProblemDetails
            {
                Status = StatusCodes.Status500InternalServerError,
                Title = "An unexpected error occurred."
            },
            cancellationToken);
        return true;
    }
}

Register the handler in Program.cs:

builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseExceptionHandler();
app.MapControllers();

Production applications should avoid returning internal exception details, database information, or stack traces to clients.

17. Testing Clean Architecture

One of the major advantages of Clean Architecture is that business logic can be tested without depending on external systems.

17.1 Domain Unit Testing

Test the business rules directly.

[Fact]
public void Product_ShouldRejectNegativePrice()
{
    Assert.Throws<ArgumentException>(
        () => new Product("Laptop", -100));
}

17.2 Application Unit Testing

Mock the repository interface and test the application use case.

[Fact]
public async Task GetProduct_ShouldReturnProduct()
{
    var product = new Product("Laptop", 55000);
    var repository = new Mock<IProductRepository>();
    repository
        .Setup(x => x.GetByIdAsync(1))
        .ReturnsAsync(product);
    var service = new ProductService(repository.Object);
    var result = await service.GetByIdAsync(1);
    Assert.NotNull(result);
    Assert.Equal("Laptop", result.Name);
}

This example assumes that the Application Service returns a Product. If the service maps the entity to a DTO, assert against the corresponding DTO properties instead.

17.3 Infrastructure Integration Testing

Test the repository implementation against a real or test database to verify that Entity Framework Core queries and persistence operations work correctly.

17.4 API Integration Testing

Test the complete HTTP request flow, including:

  • Routing.
  • Dependency injection.
  • Validation.
  • Authentication and authorization.
  • Database integration.
  • HTTP status codes and response formats.

18. Advantages and Disadvantages of Clean Architecture

Advantages

  • Maintainability: Each layer has clearly defined responsibilities.
  • Testability: Business logic can be tested independently of infrastructure.
  • Flexibility: Database and external service implementations can be replaced with less impact on core logic.
  • Reusability: Application use cases can be reused by different presentation layers.
  • Separation of Concerns: Controllers, business logic, and infrastructure are kept separate.
  • Scalability of development: Clear boundaries help larger teams work on different parts of the application.

Disadvantages

  • Initial complexity: Requires more planning and project structure.
  • More files and interfaces: Simple operations may require additional classes.
  • Learning curve: Developers must understand dependency direction and architectural boundaries.
  • Potential overengineering: Applying every pattern to a small application can increase unnecessary complexity.
  • Mapping overhead: Multiple DTOs and models may require conversion between layers.

19. Common Clean Architecture Mistakes

Mistake Why It Is a Problem
Putting business logic in controllers Controllers become difficult to test and maintain.
Referencing Infrastructure from Domain Violates dependency direction.
Using DbContext directly in Application handlers Creates direct dependence on EF Core unless deliberately accepted as an architectural trade-off.
Creating interfaces for every class Introduces unnecessary abstractions.
Duplicating business logic Creates inconsistent behavior across use cases.
Making Domain entities simple database containers Business rules may become scattered across services.
Adding CQRS and MediatR everywhere Increases complexity without always providing value.
Exposing Domain entities directly through APIs Couples external API contracts to internal models.

20. Clean Architecture Best Practices

  • Keep the Domain layer independent of external frameworks.
  • Make the Application layer responsible for coordinating use cases.
  • Define abstractions close to the layer that needs them.
  • Keep infrastructure implementations in the Infrastructure layer.
  • Use dependency injection to connect abstractions and implementations.
  • Keep controllers thin and focused on HTTP concerns.
  • Use DTOs to control API request and response contracts.
  • Protect business invariants inside Domain entities and Value Objects.
  • Use CQRS and MediatR only when they provide meaningful benefits.
  • Write unit tests for Domain and Application logic.
  • Use integration tests for database and API behavior.
  • Avoid unnecessary abstractions and excessive project separation.

21. Clean Architecture vs Other Architectures

21.1 Clean Architecture vs Layered Architecture

Clean Architecture Traditional Layered Architecture
Dependencies point inward. Dependencies commonly flow from presentation to business to data layers.
Core business logic is independent of infrastructure. Business logic may depend directly on data access implementations.
Infrastructure implements abstractions defined by inner layers. Data access is often directly referenced by business services.
Focuses strongly on dependency direction. Focuses primarily on separation into logical layers.

21.2 Clean Architecture vs Onion Architecture

Clean Architecture Onion Architecture
Organizes code around business rules and use cases. Organizes code around the Domain model.
Uses inward dependency direction. Also uses inward dependency direction.
Often emphasizes Domain, Application, Infrastructure, and Presentation. Often emphasizes Domain Model, Domain Services, Application Services, and Infrastructure.
Infrastructure implements inner-layer abstractions. Infrastructure implements abstractions defined by inner layers.

Both architectures share the same fundamental idea: business logic should not depend on infrastructure details.

21.3 Clean Architecture vs Hexagonal Architecture

Clean Architecture Hexagonal Architecture
Uses concentric layers to organize business rules and use cases. Organizes the application around ports and adapters.
Emphasizes dependency direction toward the core. Emphasizes isolating the core through ports and adapters.
Infrastructure implements interfaces required by inner layers. Adapters implement or use ports to communicate with external systems.

22. Interview Questions and Answers

Q1. What is Clean Architecture?

Clean Architecture is a software design approach that separates an application into independent layers, keeping business logic independent of infrastructure, databases, frameworks, and presentation technologies.

Q2. What are the four main layers of Clean Architecture?

  1. Domain Layer.
  2. Application Layer.
  3. Infrastructure Layer.
  4. Presentation Layer.

Q3. What is the Dependency Rule?

The Dependency Rule states that dependencies should point inward toward the core business logic. Inner layers must not depend on outer layers.

Q4. Why should the Domain layer not depend on Entity Framework Core?

The Domain layer should remain independent of infrastructure and database technologies. This allows business rules to be tested and reused without requiring Entity Framework Core or a database.

Q5. What is the responsibility of the Application layer?

The Application layer coordinates use cases, defines application workflows, validates requests, and interacts with Domain entities and external dependency abstractions.

Q6. What is the responsibility of the Infrastructure layer?

The Infrastructure layer implements technical details such as database access, Entity Framework Core repositories, email services, external APIs, caching, and file storage.

Q7. Why do we define repository interfaces in the Application layer?

The Application layer needs a way to access data without depending on a particular database implementation. Repository interfaces provide this abstraction, and Infrastructure implements them.

Q8. What is the difference between an Entity and a Value Object?

  • Entity: Has a unique identity. Two entities can have the same property values but still represent different objects.
  • Value Object: Is defined by its values rather than by a unique identity.

Q9. What is a Domain Service?

A Domain Service contains business logic that does not naturally belong to a single Entity or Value Object.

Q10. What is a DTO, and why is it used?

A DTO is a Data Transfer Object used to transfer data between application boundaries. It prevents internal Domain entities from being exposed directly and allows API contracts to evolve independently.

Q11. Can the Infrastructure layer depend on the Application layer?

Yes. The Infrastructure layer can depend on Application interfaces and implement them. This is how dependency inversion is achieved.

Q12. What is the role of Dependency Injection in Clean Architecture?

Dependency Injection connects interfaces with their implementations at runtime. It allows the Application layer to use abstractions without knowing the concrete Infrastructure implementations.

Q13. Is Repository Pattern mandatory in Clean Architecture?

No. Repository Pattern is not mandatory. It is useful when it provides a meaningful abstraction around data access. Some applications use EF Core directly in Application handlers as a deliberate trade-off, although this introduces an EF Core dependency into that layer.

Q14. What is CQRS?

CQRS stands for Command Query Responsibility Segregation. It separates operations that modify application state from operations that retrieve data.

Q15. Is MediatR mandatory in Clean Architecture?

No. MediatR is optional. It can help organize commands, queries, and handlers, but ordinary application services can also implement use cases.

Q16. How do you test the Domain layer?

Use unit tests to verify entity behavior, Value Object equality, and business rules without requiring a database or web server.

Q17. How do you test the Application layer?

Test application use cases by providing mock or fake implementations of the interfaces that the Application layer depends on.

Q18. What is the difference between Clean Architecture and Onion Architecture?

Both use inward dependency direction and protect business logic from infrastructure. Clean Architecture commonly emphasizes use cases and application boundaries, while Onion Architecture emphasizes the Domain model at the center. Their practical implementations can be very similar.

Q19. Can Clean Architecture be used with Microservices?

Yes. Each microservice can use Clean Architecture internally. The architecture helps organize that service's business logic, application workflows, and infrastructure integrations.

Q20. When should you avoid Clean Architecture?

For very small applications, simple prototypes, or short-lived services with limited business logic, a simpler architecture may be more appropriate. Clean Architecture should solve actual complexity rather than introduce unnecessary layers.

23. Summary

Clean Architecture helps build maintainable, testable, and flexible ASP.NET Core applications by separating business logic from infrastructure and presentation concerns.

  • Domain: Contains entities, Value Objects, Domain Services, and business rules.
  • Application: Contains use cases, DTOs, application services, and interfaces.
  • Infrastructure: Contains EF Core, database access, repositories, and external integrations.
  • Presentation: Contains ASP.NET Core controllers, endpoints, and HTTP-related functionality.
  • Dependency Rule: Dependencies point inward toward the core business logic.
  • Dependency Injection: Connects abstractions to their implementations.
  • CQRS and MediatR: Optional patterns and libraries that can help organize application use cases.

24. Conclusion

Clean Architecture is especially useful for enterprise applications with complex business rules, multiple integrations, and long-term maintenance requirements.

In ASP.NET Core, separating Domain, Application, Infrastructure, and Presentation responsibilities helps developers build applications that are easier to test, maintain, extend, and adapt to changing technical requirements.

The most important principle is not the number of projects or folders. It is keeping business logic independent of external implementation details.

🔙
EF Core Performance Optimization :👈 👉:ASP.NET Core Dependency Injection