Skip to content

C# Interview Guide: Clean Architecture — Solution Structure and the Dependency Rule

Q26 — Clean Architecture — Solution Structure, Dependency Rule, Layer Responsibilities Level: Senior | Topic: Architecture The Core Principle — Dependency Rule In Clean Architecture, dependencies point inward only . The ...

Ekanatha Reddy Urivakili11 min1,488 words

Q26 — Clean Architecture — Solution Structure, Dependency Rule, Layer Responsibilities

Level: Senior | Topic: Architecture

Clean Architecture, championed by Robert C. Martin (Uncle Bob), continues to be a foundational approach for designing maintainable, testable, and framework-independent applications. This article expands on the core principle of the dependency rule, explains each layer's responsibility, and illustrates the solution's folder structure, supported by diagrams, tables, and practical C# code.


The Core Principle — Dependency Rule

Clean Architecture’s fundamental rule is simple yet powerful: all source code dependencies must point inward toward higher-level policies and abstractions — never outward. This is often referred to as the Dependency Rule.

flowchart LR
  D[Domain Layer] --> A[Application Layer]
  A --> I[Infrastructure Layer]
  A --> API[API Layer]
  style D fill:#f9f,stroke:#333,stroke-width:2px
  style A fill:#ccf,stroke:#333,stroke-width:2px
  style I fill:#cfc,stroke:#333,stroke-width:2px
  style API fill:#fcf,stroke:#333,stroke-width:2px

Diagram: Dependency direction flows inward from outer layers (API, Infrastructure) toward inner layers (Application, Domain).

This inward-only dependency ensures that:

  • The Domain layer is free from external dependencies and frameworks.
  • The Application layer depends on the Domain but remains free of infrastructure concerns.
  • Infrastructure implements interfaces defined in Domain or Application but never influences their code.
  • The API layer wires everything together but does not contain business logic.

Layer Responsibilities in Detail

Layer Contents Dependencies Purpose
Domain Entities, Value Objects, Aggregates, Domain Events, Repository Interfaces, Domain Exceptions None Core business logic, rules, and policies; the heart of the system
Application Use Cases, CQRS Commands & Queries, DTOs, Validators, Pipeline Behaviors Domain only Orchestrates domain logic to serve application goals; no infrastructure knowledge
Infrastructure Database EF Core, Redis, HTTP Clients, Message Bus, Implementations of Domain Interfaces Domain + external frameworks (EF Core, cloud SDKs) Implementations for persistence, messaging, caching, and other external systems
API Controllers, Middleware, DI Container Wiring, Program.cs Application + Infrastructure (for wiring) Exposes system via HTTP endpoints and coordinates services

High-Level Solution Structure

flowchart TD
  subgraph Domain [MyApp.Domain]
    E1[Entities]
    VO1[Value Objects]
    EV1[Domain Events]
    R1[Repository Interfaces]
    EX1[Domain Exceptions]
  end

  subgraph Application [MyApp.Application]
    UC1[Use Cases]
    D1[DTOs]
    B1[Behaviours (Logging, Validation)]
  end

  subgraph Infrastructure [MyApp.Infrastructure]
    P1[Persistence (EF Core)]
    M1[Messaging]
    C1[Caching]
  end

  subgraph API [MyApp.Api]
    CT1[Controllers]
    MW1[Middleware]
    PR1[Program.cs]
  end

  E1 --> UC1
  VO1 --> UC1
  EV1 --> UC1
  R1 --> P1
  UC1 --> P1
  UC1 --> CT1
  P1 --> MW1
  MW1 --> PR1

Diagram: Layers with examples of artifact grouping and direction of dependencies.


Sequence of a Typical Request Through Layers

sequenceDiagram
  participant Client
  participant Controller as API Controller
  participant UseCase as Application UseCase
  participant Domain as Domain Entities
  participant Repo as Repository (Infra)
  participant DB as Database

  Client->>Controller: HTTP Request (PlaceOrder)
  Controller->>UseCase: Execute PlaceOrderCommand
  UseCase->>Domain: Create/Update Order entity
  Domain-->>UseCase: Returns Order with enforced business logic
  UseCase->>Repo: Save Order (via IOrderRepository)
  Repo->>DB: Persist data
  DB-->>Repo: Success
  Repo-->>UseCase: Confirmation
  UseCase-->>Controller: Result
  Controller-->>Client: HTTP Response

Diagram: Walkthrough of order placing command showing controlled dependency flow.


Domain Entity Example — Rich Domain Model

// Pure C# — no EF, no ASP.NET, no framework references
public class Order : AggregateRoot<OrderId>
{
    private readonly List<OrderLine> _lines = new();

    public CustomerId CustomerId { get; private set; }
    public OrderStatus Status { get; private set; }
    public Money Total => Money.Sum(_lines.Select(l => l.LineTotal));

    // Factory method — enforces invariants at creation
    public static Order Create(CustomerId customerId, IEnumerable<OrderLine> lines)
    {
        var lineList = lines.ToList();
        if (!lineList.Any())
            throw new DomainException("Order must have at least one line");

        var order = new Order
        {
            Id = OrderId.New(),
            CustomerId = customerId,
            Status = OrderStatus.Draft
        };
        order._lines.AddRange(lineList);
        order.RaiseDomainEvent(new OrderCreatedEvent(order.Id, customerId));
        return order;
    }

    // Domain behaviour — guards business rules
    public void Submit()
    {
        if (Status != OrderStatus.Draft)
            throw new DomainException($"Cannot submit order in {Status} status");
        Status = OrderStatus.Submitted;
        RaiseDomainEvent(new OrderSubmittedEvent(Id));
    }
}

Notice how this class uses internal state protection, business invariants, and raises domain events without external dependencies.


Application Layer Example — Command Handler with Dependency Injection and Validation

using MediatR;
using FluentValidation;
using MyApp.Domain.Repositories;

public class PlaceOrderCommand : IRequest<OrderDto>
{
    public Guid CustomerId { get; init; }
    public IList<OrderLineDto> Lines { get; init; }
}

public class PlaceOrderHandler : IRequestHandler<PlaceOrderCommand, OrderDto>
{
    private readonly IOrderRepository _orderRepository;

    public PlaceOrderHandler(IOrderRepository orderRepository)
    {
        _orderRepository = orderRepository;
    }

    public async Task<OrderDto> Handle(PlaceOrderCommand request, CancellationToken cancellationToken)
    {
        var orderLines = request.Lines.Select(l =>
            new OrderLine(
                ProductId.New(l.ProductId),
                l.Quantity,
                Money.FromDecimal(l.Price)
            )).ToList();

        var order = Order.Create(CustomerId.New(request.CustomerId), orderLines);
        await _orderRepository.AddAsync(order, cancellationToken);

        return new OrderDto
        {
            Id = order.Id.Value,
            CustomerId = order.CustomerId.Value,
            Total = order.Total.Amount
        };
    }
}

public class PlaceOrderValidator : AbstractValidator<PlaceOrderCommand>
{
    public PlaceOrderValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.Lines).NotEmpty();
        RuleForEach(x => x.Lines).SetValidator(new OrderLineValidator());
    }
}

public class OrderLineValidator : AbstractValidator<OrderLineDto>
{
    public OrderLineValidator()
    {
        RuleFor(x => x.ProductId).NotEmpty();
        RuleFor(x => x.Quantity).GreaterThan(0);
        RuleFor(x => x.Price).GreaterThan(0);
    }
}

This example shows the Application layer’s responsibility: orchestrating domain logic, validating inputs, and deferring persistence to Infrastructure via repository interface.


Infrastructure Layer Example — EF Core Repository Implementation

using Microsoft.EntityFrameworkCore;
using MyApp.Domain.Entities;
using MyApp.Domain.Repositories;

public class EfOrderRepository : IOrderRepository
{
    private readonly AppDbContext _context;

    public EfOrderRepository(AppDbContext context)
    {
        _context = context;
    }

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

    public async Task<Order?> GetByIdAsync(OrderId id, CancellationToken ct)
    {
        return await _context.Orders
            .Include(o => o.Lines)
            .FirstOrDefaultAsync(o => o.Id == id, ct);
    }
}

Notice how the repository implements only the interface defined in the Domain layer, allowing full substitution in tests and no leakage of EF Core types into Domain or Application.


Observability in Clean Architecture

Proper observability and tracing are critical for complex distributed systems implementing this architecture.

What to Log

  • Entry and exit of Use Cases/Handlers with correlation IDs.
  • Domain event emissions.
  • Repository calls to external systems.
  • Infrastructure exceptions and retries.

Structured logging example in Application layer:

{
  "Timestamp": "2024-06-16T12:34:56Z",
  "Level": "Information",
  "Message": "Order placed successfully",
  "OrderId": "123e4567-e89b-12d3-a456-426614174000",
  "CustomerId": "789e4567-e89b-12d3-a456-426614174111",
  "CorrelationId": "corr-foo-bar-123"
}

Key Metrics (RED & USE Framework)

Metric CategoryMetricDescription
R (Reliability)Request success ratePercentage of successful end-to-end requests
E (Errors)Domain errors per operationBusiness rule violation counts
D (Duration)Handler execution timeMedian and P95 latency for CQRS handlers
U (Utilization)CPU, Memory usageFor API and Infrastructure hosts
S (Saturation)Database connection pool usage% utilization of DB pools
E (Errors)DB connection failuresFailure counts and rate

Distributed Tracing with OpenTelemetry (C# example)

using OpenTelemetry.Trace;
using OpenTelemetry.Resources;

var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyApp.Api"))
    .AddAspNetCoreInstrumentation()
    .AddHttpClientInstrumentation()
    .AddSource("MyApp.Application")
    .AddJaegerExporter()
    .Build();

Instrument Application and Infrastructure layers. Use tracing to correlate logs and diagnose layer-crossing calls.


SLI / SLO Table Example for Critical API Endpoint: PlaceOrder

SLISLONotes
Request success rate>= 99.9%Exclude client errors (4xx)
P95 latency for PlaceOrder API< 300 msMeasured at API gateway
Domain violation rate< 0.01%Business rule violations
Database error rate< 0.01%Connection and query errors

Senior Insights & Best Practices

  • Keep the domain pure: Many systems suffer from an Anemic Domain Model — placing business rules in Application or even Infrastructure layers, robbing the domain of its richness.
  • Use abstractions and interfaces: Define repository contracts in Domain to decouple persistence implementations.
  • Inject dependencies via constructor: Favor explicitness and immutability.
  • Test domain models independently: Write in-memory, framework-free tests focused on business invariants.
  • Application handlers: Keep them thin orchestration layers that coordinate validation, security, and domain calls.
  • Infrastructure as implementation detail: Can be switched without touching Domain or Application layers, supporting multi-database or messaging systems.
  • API layer: Minimal logic, primarily routing, authorization, and request/response transformation.

Summary

Clean Architecture emphasizes inward-pointing dependencies with a pure Domain layer at the center, unaffected by frameworks and infrastructure. This results in:

  • Highly testable and maintainable code.
  • Clear separation of concerns.
  • Flexibility to change frameworks, UI, or infrastructure independently.
  • Rich domain models that embody true business rules and behavior.

The structured folder layout, dependency enforcement, and layer responsibilities shown here provide a real-world blueprint for modern C# applications using EF Core, MediatR, FluentValidation, and OpenTelemetry tracing.


References


Advanced Internal Mechanics of Dependency Resolution and Decoupling

Achieving the strict inward dependency flow at compile time is conceptually straightforward but practically challenging given complex real-world dependency graphs and cross-cutting concerns. Understanding how dependencies are resolved and still preserve the Dependency Rule requires delving into several subtle points:

1. Dependency Inversion and Interface Segregation Synergy

While the Domain layer defines repository interfaces, the Application layer depends on those interfaces, never implementations. Infrastructure concretely implements those interfaces.

This implies a multi-step indirection:

  • Domain → defines abstractions (interfaces)
  • Application → orchestrates use cases using Domain abstractions (interfaces)
  • Infrastructure → binds implementation to those interfaces via DI container

This aligns with the Dependency Inversion Principle (DIP), but relies heavily on well-segregated, granular interfaces:

  • Large, coarse-grained interfaces tend to bind layers tightly.
  • Fine-grained interfaces encourage extensional flexibility but can increase interface proliferation and wiring complexity.

2. Dependency Injection Container as the Composition Root

Because Infrastructure implements interfaces but cannot be referenced inward from Application or Domain, the injection of implementations happens only at the entry point, in the API layer or a dedicated Composition Root project.

+-------------------+
|       API Layer    |  -- Composition Root -- injects implementations
+-------------------+
          |
  (Dependency injection wiring)
          |
+-------------------+
| Application Layer  |  -- depends on interfaces from Domain
+-------------------+
          |
+-------------------+
|   Domain Layer     |  -- pure abstractions, no implementations
+-------------------+
          |
+-------------------+
| Infrastructure Layer | -- implements abstractions, references external frameworks
+-------------------+  (references only Domain and Application interfaces, no inverse)

This architecture requires attention to avoid circular references or runtime injection failures:

  • Injected implementations must not leak framework details to Application.
  • Abstractions must be stable and minimal enough to cover necessary functionality without exposing internals.

3. Factory Pattern for Polymorphic Domain Object Creation

Sometimes domain entities require complex creation that might seemingly depend on infrastructure concerns (e.g., generating IDs, date/time, or external data).

To keep Domain isolated:

  • Delegate such concerns to factories external to Domain, wired via dependency injection in Application.
  • Pass fully formed primitives or value objects when instantiating entities.

Example interface defined in Domain:

public interface IOrderIdFactory
{
    OrderId NewId();
}

Infrastructure implements this interface injecting, say, a GUID generator or Distributed ID generator.

Application orchestrates together:

var orderId = _orderIdFactory.NewId();
var order = Order.Create(orderId, customerId, lines);

This preserves a pure Domain while allowing Domain to be instantiated flexibly.

4. Cross-Layer Events and Message Passing

Domain events notify Application or Infrastructure about state changes while remaining decoupled.

  • Domain raises events via a base mechanism (e.g., RaiseDomainEvent).
  • Application layer consumes these events to initiate side effects like notifications or eventual consistency workflows.
  • Infrastructure listens to domain events for persistence side effects (e.g., event sourcing or pub/sub).

This event model avoids pulling in infrastructure concerns into the Domain at runtime or code time, using event dispatchers implemented in Application or Infrastructure.


Complex Production Scenario: Distributed Transaction with Outbox Pattern

Consider a real system scenario where placing an order not only stores data but publishes an integration event to an external message broker (Kafka, RabbitMQ) for downstream systems like Warehouse, Billing, and Notification.

Challenges

  • Domain model must not depend on infrastructure message brokers.
  • Transactions span database and message broker — classic distributed transaction.
  • Must guarantee atomicity in eventual consistency terms (no order without message, no message without order).

Solution: Outbox Pattern with Clean Architecture

  1. Domain layer defines event types and raises domain events on aggregate changes (OrderCreatedEvent).

  2. Application layer orchestrates the handler, commits DbContext transaction, collects domain events for publishing.

  3. Infrastructure layer implements:

    • A repository saving order and outbox messages (persisted side table).
    • A background process (worker service) that reads pending outbox messages and publishes them to message broker reliably.

Example Workflow

sequenceDiagram
  participant Client
  participant API
  participant Application
  participant Domain
  participant Repository
  participant Db
  participant Outbox
  participant MessageBroker
  participant DownstreamServices

  Client->>API: HTTP PlaceOrder
  API->>Application: Invoke PlaceOrderHandler
  Application->>Domain: Create Order + Raise Domain Events
  Application->>Repository: Save Order + Enqueue Outbox message (single TX)
  Repository->>Db: Commit Transaction
  Db-->>Repository: Commit Success
  Repository-->>Application: Confirmation
  Application-->>API: Return Result
  Note over Repository,Outbox: Separate Worker picks up outbox messages
  Outbox->>MessageBroker: Publish Events
  MessageBroker->>DownstreamServices: Deliver Events

Code Snippet: Outbox Entity in Infrastructure

public class OutboxMessage
{
    public Guid Id { get; set; }
    public string Type { get; set; } = null!;
    public string Payload { get; set; } = null!;
    public DateTime OccurredOn { get; set; }
    public bool Processed { get; set; }
}

public class EfOrderRepository : IOrderRepository
{
    private readonly AppDbContext _context;

    public EfOrderRepository(AppDbContext context)
    {
        _context = context;
    }

    public async Task AddAsync(Order order, IEnumerable<DomainEvent> domainEvents, CancellationToken ct)
    {
        _context.Orders.Add(order);

        foreach (var evt in domainEvents)
        {
            _context.OutboxMessages.Add(new OutboxMessage()
            {
                Id = Guid.NewGuid(),
                Type = evt.GetType().Name,
                Payload = JsonSerializer.Serialize(evt),
                OccurredOn = DateTime.UtcNow,
                Processed = false,
            });
        }

        await _context.SaveChangesAsync(ct);
    }
}

Note how Infrastructure supports transactions that include both domain data and integration event persistence atomically.

Worker for Outbox Processing (Infrastructure Hosted Service)

public class OutboxPublisherService : BackgroundService
{
    private readonly AppDbContext _context;
    private readonly IMessageBrokerClient _brokerClient;

    public OutboxPublisherService(AppDbContext context, IMessageBrokerClient brokerClient)
    {
        _context = context;
        _brokerClient = brokerClient;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var eventsToProcess = await _context.OutboxMessages
                .Where(e => !e.Processed)
                .ToListAsync(stoppingToken);

            foreach (var evt in eventsToProcess)
            {
                await _brokerClient.PublishAsync(evt.Type, evt.Payload, stoppingToken);
                evt.Processed = true;
            }

            await _context.SaveChangesAsync(stoppingToken);
            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
        }
    }
}

This pattern effectively decouples domain transactions from eventual publish guarantees without violating Clean Architecture principles.


Handling Edge Cases, Failure Modes, and Performance Pitfalls

Real systems depart from ideal and must handle intermittent failures, partial data, performance bottlenecks, and transactional edge conditions gracefully.

Important Edge Cases

ScenarioClean Architecture Handling
Partial Failure in InfrastructureApplication retries or compensating actions triggered; Domain never sees partial state.
Domain Validation FailuresEarly rejection in Application validation layer prevents expensive calls downstream.
Concurrency Conflicts in DBInfrastructure reports conflicts; Application handles retries or asks user for input.
Missing Infrastructure ServicesFail open or degraded mode implemented in Infrastructure, Application displays graceful errors.
Eventual Consistency DelaysDomain and Application designed for asynchronous workflows; UI indicates processing state.

Failure Mode Example: Infrastructure DB downtime during Save

Clean Architecture encourages:

  • Retries with exponential backoff in Infrastructure layer.
  • Circuit breakers to prevent saturation of resources.
  • Application layer catches repository exceptions and converts to user-friendly error response.
  • Domain methods are pure and will never throw unexpected infra exceptions.

Performance Considerations

  • Avoid chatty interactions across layers — batch domain events and repository operations.
  • Domain entities should not carry heavy state or collections — aggregate size limits improve memory usage and serialization performance.
  • Infrastructure caching (Redis, in-memory caches) should be behind interfaces without leaking caching details into Application or Domain.
  • MediatR pipeline behaviors are an excellent place to add logging, validation, and authorization without polluting domain or application code.

Observability Deep Dive: Layer-Specific Guidance and OpenTelemetry Integration

To maintain high maintainability in production systems, observability must be embedded across layers, not just API entry points.

What to Log

LayerLog ContentFormat Recommendation
DomainDomain event emissions, business invariant violations, aggregate lifecycleStructured logs with entity ID and event type
ApplicationUse case start/end, validation decisions, authorization resultsInclude Correlation IDs, input DTO snapshots
InfrastructureRepository calls success/failure, external service calls, retriesDetailed error codes, latency, service names
APIHTTP request/response details, routing info, middleware eventsInclude user context and request identifiers

Structured Log Example with Semantic Fields (Application Layer)

{
  "Timestamp": "2024-06-16T16:22:30Z",
  "Level": "Information",
  "Logger": "PlaceOrderHandler",
  "Message": "Order placed successfully",
  "OrderId": "123e4567-e89b-12d3-a456-426614174000",
  "CustomerId": "789e4567-e89b-12d3-a456-426614174111",
  "CorrelationId": "corr-foo-bar-123",
  "ExecutionTimeMs": 125,
  "Outcome": "Success"
}

Key Metrics per Layer (Expanded RED & USE)

LevelMetricSource LayerCollection Method
ReliabilityUse case success/failure ratioApplicationCount exceptions per handler
ErrorsDomain validation failuresDomain/ApplicationReturn codes or exceptions
DurationMedian, P95 CQRS command latencyApplicationStopwatch timers in pipeline
UtilizationCPU, memory per serviceAPI, InfrastructureHost OS or container metrics
SaturationDB/PubSub connection pool usageInfrastructureDatabase & message broker stats
ErrorsInfrastructure transient faultsInfrastructureCircuit breaker open events

OpenTelemetry Tracing Integration Code (Application + Infrastructure)

using OpenTelemetry.Trace;
using OpenTelemetry.Resources;

var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("MyApp", serviceVersion: "1.0.0"))
    .AddSource("MyApp.Domain", "MyApp.Application", "MyApp.Infrastructure")
    .AddAspNetCoreInstrumentation()
    .AddHttpClientInstrumentation()
    .AddEntityFrameworkCoreInstrumentation()
    .AddJaegerExporter(o =>
    {
        o.AgentHost = "jaeger-agent";
        o.AgentPort = 6831;
    })
    .Build();

In domain or application code, instrument critical methods:

private static readonly ActivitySource ActivitySource = new("MyApp.Application");

public async Task<OrderDto> Handle(PlaceOrderCommand request, CancellationToken cancellationToken)
{
    using var activity = ActivitySource.StartActivity("Handle PlaceOrder");

    // Business logic here

    activity?.SetTag("order.id", order.Id.Value);
    activity?.SetTag("customer.id", request.CustomerId);
    // ...
    return result;
}

Tracing correlated with logs and metrics creates a comprehensive observability triad critical to diagnosing issues and improving reliability.


Decision Checklist: When and How to Use Clean Architecture in C#

Before adopting this layered approach, consider:

ConcernQuestions to AskClean Architecture Fit
System ComplexityDoes my system have complex business rules?Yes, domain-driven design benefits
Team Size and SkillsDoes team understand layered architecture and DI?Necessary to enforce boundaries
Framework vs. Business LogicDo I want framework independence and testability?Yes, promotes isolating framework code
Speed of DeliveryIs rapid prototyping more important than strict boundaries?Maybe favors simpler approaches
Deployment/OperationsWill infrastructure or UI change frequently?Clean Architecture offers flexibility
Performance ConstraintsDoes the indirection overhead matter?Usually negligible, but profile if needed
Legacy IntegrationDoes legacy code violate layering or require compromise?May need anti-corruption layers
Observability RequirementsWill tracing and logging span multiple layers?Architecture makes instrumentation clearer

Carefully weigh these factors and establish pragmatic layering rules to maximize value while minimizing complexity overhead.


Each of these sections extends the conceptual foundations presented in the original article with practical insights, real-world production readiness strategies, and deep observability considerations aligned with modern C# enterprise development. This will prepare engineers not only to understand but also to implement, maintain, and evolve systems built on Clean Architecture principles.