Module 1 · Basics · Lesson 1 of 14
Clean Architecture in .NET: The Dependency Rule Interviewers Ask About
What this lesson teaches
Clean Architecture in .NET keeps business rules independent of the UI and database. Learn the dependency rule and how the core can still save data.
The UI, or user interface, is the part people use to interact with an application. The core contains the business rules and the operations the application supports.
After this lesson, you can explain:
- What must point inward, and what can still call outward.
- How Clean, onion and hexagonal architecture relate.
- Where EF Core belongs.
- How to check whether code breaks the dependency rule.
If you need a refresher first, read dependency inversion, dependency injection and IoC in C#.
What is Clean Architecture?
Clean Architecture puts business rules at the centre and makes outside details depend on them. A dependency exists when one piece of code needs another type or library to compile.
The dependency rule says that source-code dependencies point inward, toward the business rules. The core must not need the UI or database implementation to compile.
Think of an order rule: an order must contain at least one item. That rule does not need to know whether orders arrive from a website or a console. It also does not need to know which database stores them.
We will use three parts:
- Domain contains business concepts and rules, such as an order and its allowed quantity.
- Application contains use cases. A use case is one operation the application supports, such as placing an order.
- Infrastructure contains implementations that deal with outside details, such as database storage.
Robert C. Martin’s four circles are Entities, Use Cases, Interface Adapters, and Frameworks and Drivers. Entities hold business rules, and use cases coordinate application operations. Interface adapters translate data between the core and outside code. Frameworks and drivers are outside technologies, such as a web framework or database. These circles are a picture of responsibilities, not a required project count. .NET solutions often name their projects Domain, Application, Infrastructure and Web/API.
flowchart TD
U["UI"] -->|"depends on"| A["Application"]
P["Program startup"] -.->|"wires (startup only)"| I["Infrastructure"]
I -->|"depends on"| A
A -->|"depends on"| D["Domain"]
Solid arrows show source-code dependencies, not call order. The dashed arrow is a source dependency too, but only startup code (the composition root) may have it.
This arrangement lets you test business rules without starting the UI or connecting to a database. It does not remove the need to test the database implementation separately.
The mistake to avoid. Do not define Clean Architecture by folder names. A folder called Domain provides no protection if its code still depends on database details.
In an interview, say: “Clean Architecture puts business rules at the centre, with source dependencies pointing inward. Martin’s circles are Entities, Use Cases, Interface Adapters, and Frameworks and Drivers. Four projects are not mandatory. In .NET, common project names are Domain, Application, Infrastructure and Web/API.”
Why not just use layers?
A layer groups code by responsibility. In a traditional N-layer design, UI calls the business logic layer, or BLL, which calls the data access layer, or DAL.
When source dependencies follow that same direction, the business logic depends on the data access implementation. Testing a price calculation may then require constructing database-related objects or providing a test database.
Microsoft’s architecture guide describes this problem and the alternative: define the required operations in the core, then implement them outside it.
Here, a contract is an interface: it lists the methods the core needs, without saying how they work.
This is dependency inversion: business code defines the contract it needs instead of depending on the outside implementation.
Clean Architecture is not the opposite of layering. It changes the direction of dependencies between responsibilities.
Hexagonal architecture, also called ports and adapters, puts the application in the middle. It talks to the outside world through interfaces called ports. Adapters connect those ports to outside callers or technologies, such as a console or database.
Alistair Cockburn introduced hexagonal architecture in 2005. Jeffrey Palermo introduced onion architecture in 2008, and Robert C. Martin introduced Clean Architecture in 2012.
They share the goal of protecting business logic from outside details. They draw different pictures and use different names. Hexagonal talks about an inside and an outside joined by ports. Onion and Clean draw rings, with the domain in the centre.
The mistake to avoid. Do not say that every layered application requires a database for every test. The problem is business logic that depends directly on data access details, not using layers at all.
In an interview, say: “All three share the inward dependency rule. Cockburn’s hexagonal architecture uses ports and adapters. Palermo’s onion architecture and Martin’s Clean Architecture draw rings. All keep business logic independent of outside implementations.”
How the core saves an order
If the core cannot depend on a database implementation, how can it save anything?
It owns an interface describing the operation it needs. An outside class implements that interface. Startup code supplies that implementation to the use case.
In this example, IOrderStore is a port: it describes the saving operation that PlaceOrder calls. An adapter connects that contract to a particular technology or caller. Microsoft’s architecture guide also discusses the hexagonal, or ports-and-adapters, approach.
A driving port exposes an operation that something outside initiates. Here, PlaceOrder.Execute is the entry point that the console calls. A driven port describes something the application needs to call. Here, that is IOrderStore. In the example, the console code is a driving adapter. InMemoryOrderStore is a driven adapter.
Here, the startup code that creates the store and passes it to PlaceOrder is the composition root. Supplying an implementation from outside is dependency injection. This example does it directly through a constructor, without a package.
A DTO, or data transfer object, carries data between parts of an application without carrying database behaviour. The example uses simple records for its input and saved data. A record is a C# type designed for data, with compiler-provided equality based on its contents.
There is also a small architecture check. An architecture test checks a structural rule, such as which parts may depend on Infrastructure. Reflection lets a running program inspect types and their members.
Run this as one .NET 10 console program. Before running it, predict three results: the clean check, the deliberately broken check, and the check of a dependency hidden inside a method.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
var store = new Infrastructure.InMemoryOrderStore();
var placeOrder = new Application.PlaceOrder(store);
var saved = placeOrder.Execute(new Application.PlaceOrderRequest(2));
Console.WriteLine($"Saved orders: {store.Count}; total: {saved.Total:0}");
var cleanTypes = new[]
{
typeof(Domain.Order),
typeof(Application.PlaceOrder),
typeof(Application.IOrderStore),
typeof(Application.PlaceOrderRequest),
typeof(Application.OrderData)
};
Report("Clean core", FindViolations(cleanTypes));
Report("Planted property", FindViolations(typeof(Domain.BadOrder)));
Report("Body-only dependency", FindViolations(typeof(Domain.BodyOnlyProbe)));
static void Report(string name, IEnumerable<string> violations)
{
var found = violations.ToArray();
Console.WriteLine($"{name}: {(found.Length == 0 ? "PASS" : "FAIL")}");
foreach (var violation in found)
Console.WriteLine(violation);
}
static IEnumerable<string> FindViolations(params Type[] types)
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic
| BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
foreach (var type in types)
{
if (type.Namespace is not ("Domain" or "Application"))
continue;
var referenced = new List<Type>();
referenced.AddRange(type.GetFields(flags).Select(f => f.FieldType));
referenced.AddRange(type.GetProperties(flags).Select(p => p.PropertyType));
foreach (var method in type.GetMethods(flags))
{
referenced.Add(method.ReturnType);
referenced.AddRange(method.GetParameters().Select(p => p.ParameterType));
}
foreach (var constructor in type.GetConstructors(flags))
referenced.AddRange(constructor.GetParameters().Select(p => p.ParameterType));
foreach (var dependency in referenced.Distinct())
{
if (dependency.Namespace == "Infrastructure")
yield return $"{type.FullName} -> {dependency.FullName}";
}
}
}
namespace Domain
{
public sealed class Order
{
public int Quantity { get; }
public decimal Total => Quantity * 10m;
public Order(int quantity)
{
if (quantity < 1)
throw new ArgumentOutOfRangeException(nameof(quantity));
Quantity = quantity;
}
}
// Deliberate violation: excluded from the clean check above.
public sealed class BadOrder
{
public Infrastructure.InMemoryOrderStore Store => new();
}
// Another violation, hidden inside a method body.
public sealed class BodyOnlyProbe
{
public int ReadCount()
{
var store = new Infrastructure.InMemoryOrderStore();
return store.Count;
}
}
}
namespace Application
{
public sealed record PlaceOrderRequest(int Quantity);
public sealed record OrderData(int Quantity, decimal Total);
public interface IOrderStore
{
void Save(OrderData order);
}
public sealed class PlaceOrder
{
private readonly IOrderStore _store;
public PlaceOrder(IOrderStore store) => _store = store;
public OrderData Execute(PlaceOrderRequest request)
{
var order = new Domain.Order(request.Quantity);
var data = new OrderData(order.Quantity, order.Total);
_store.Save(data);
return data;
}
}
}
namespace Infrastructure
{
public sealed class InMemoryOrderStore : Application.IOrderStore
{
private readonly List<Application.OrderData> _orders = new();
public int Count => _orders.Count;
public void Save(Application.OrderData order) => _orders.Add(order);
}
}Saved orders: 1; total: 20 Clean core: PASS Planted property: FAIL Domain.BadOrder -> Infrastructure.InMemoryOrderStore Body-only dependency: PASS
First, startup creates the store and passes it to PlaceOrder. This is the composition root. Only this startup code needs to name the real class, InMemoryOrderStore. The use case uses only the IOrderStore interface.
Next, Execute creates a domain order, whose constructor rejects quantities below one. It copies the data into OrderData and calls _store.Save(data). With quantity two at ten each, the first output reports one saved order and a total of twenty.
The important distinction is between a call and a source dependency. During execution, PlaceOrder calls an Infrastructure implementation. In its source code, however, PlaceOrder names only the core-owned IOrderStore contract.
classDiagram
namespace Application {
class PlaceOrder {
+Execute(PlaceOrderRequest) OrderData
}
class IOrderStore {
<<interface>>
+Save(OrderData order)
}
}
namespace Infrastructure {
class InMemoryOrderStore {
+int Count
+Save(OrderData order)
}
}
PlaceOrder --> IOrderStore : calls Save
InMemoryOrderStore ..|> IOrderStore : implements
PlaceOrder calls through IOrderStore. The arrow from InMemoryOrderStore points inward: Infrastructure depends on Application’s contract.
The clean check examines only the listed legitimate core types and passes. The next check examines BadOrder and reports its forbidden Infrastructure property. That class is deliberately broken; it is not part of the proposed design.
The last check passes even though BodyOnlyProbe breaks the rule. The forbidden type appears only inside its method body. Our checker examines declared fields, properties, return types and parameter types, including constructor parameters. It does not inspect method bodies.
The mistake to avoid. Do not say “calls only go inward.” The rule concerns source-code dependencies. An outward call through a core-owned interface is how the core reaches storage without depending on its implementation.
In an interview, say: “The core defines an interface for saving data. Infrastructure implements it, and startup wires the implementation into the use case. The call can go outward while the source dependency still points inward.”
Where EF Core and boundary data belong
EF Core belongs in Infrastructure in this design. That includes DbContext, database-specific configuration and migrations. DbContext is the EF Core class that manages database connections, tracks objects and saves changes. Migrations describe changes used to bring a database structure up to date.
Replacing the example’s list with EF Core should change the store implementation, not make PlaceOrder depend on DbContext.
A boundary separates parts with different responsibilities or dependency rules. For example, the line between the use case and the database code is a boundary. Across an outer boundary, pass simple DTOs containing the data the operation needs. Do not pass database rows or EF-specific objects into the use case.
For example, a database-backed adapter could copy OrderData into the class it saves to the database table. The core would still own the contract and data shape.
Be precise about “EF entities.” A plain domain class does not become Infrastructure code merely because EF Core maps it. With a rich domain model, a storage contract often takes and returns the domain object itself, such as an Order aggregate. The problem is making core contracts depend on EF-specific behaviour or storage shapes.
This separation costs translation code and sometimes additional types. It is worth it when it protects important business rules. You do not need to copy objects every time one core method calls another.
The mistake to avoid. Moving DbContext into an Infrastructure folder is not enough if application code still accepts it or exposes database-shaped results.
In an interview, say: “EF Core’s context, mappings and migrations belong in Infrastructure. The core sees its own contracts and boundary data, not EF-specific objects. Infrastructure translates between those contracts and storage.”
How to enforce the dependency rule
A project reference lets one project compile against another project’s types. In a multi-project solution, allow Infrastructure to reference the core, but do not give the core a reference to Infrastructure.
Our example uses namespaces in one project to stay runnable as one file. Namespaces alone do not restrict access. That is why both planted violations compile.
Use several checks together:
- Project references restrict which projects the core can use.
- Internal types limit access to implementation details. In C#,
internalnormally restricts access to the same assembly. An assembly is a compiled .NET output containing code and type information. - Architecture tests detect forbidden relationships automatically.
- Code reviews catch inappropriate contracts and responsibilities that structural checks cannot judge.
Run architecture tests in continuous integration, or CI: the automated build and test process used when code changes are submitted.
Treat the sample reflection check as a demonstration, not a complete enforcement tool. Besides ignoring method bodies, it checks direct type names in exact namespaces. It does not recursively inspect types contained inside collections or cover every possible relationship.
The mistake to avoid. A passing architecture test proves only what that test actually checks. The body-only example shows why a green result cannot replace project boundaries and review.
In an interview, say: “I enforce inward dependencies with project references, internal implementation types, architecture tests in CI, and reviews. I also check what the tests inspect. A check that looks only at member types, return types and parameter types can miss dependencies inside method bodies.”
When is Clean Architecture overkill?
Clean Architecture also has a cost. Interfaces, boundary data and separate implementations add code. Splitting these responsibilities into more projects adds setup. There is also indirection: you must follow an interface to its implementation to see what an operation does.
For a small application that mainly reads and writes a few tables, a simpler design is often easier to maintain. Clean Architecture Solution Structure in .NET shows how to decide when a layer earns its place.
In an interview, say: “Clean Architecture can mean more projects, interfaces, mapping code and indirection. It can be overkill for a small CRUD application—one that mainly creates, reads, updates and deletes records. I use it when important business rules need isolation and independent tests.”
Check yourself
A PlaceOrder use case calls an Infrastructure store through IOrderStore, which is defined in Application. Does this break the dependency rule?
Show answer
Correct answer: D
The rule concerns source dependencies. Infrastructure implements the core-owned contract, and the use case can call that implementation without naming its concrete type.
Option A: Calls can go outward through a core-owned interface. Source dependencies must point inward.
Option B: The core owns the storage contract it needs. Infrastructure supplies its implementation.
Option C: Interfaces are dependencies too. The important point is that this interface belongs to the core.
The sample reflection check passes for a core class. What can you conclude?
Show answer
Correct answer: A
This check examines selected member types. It does not inspect method bodies or prove the entire architecture correct.
Option B: Infrastructure references inside method bodies are not inspected.
Option C: The check examines dependencies, not whether database operations work correctly.
Option D: Passing a limited check does not make an outward core dependency acceptable.
Going deeper
Clean Architecture Solution Structure in .NET maps this rule onto projects, including Microsoft’s three-project layout and the startup project’s reference to Infrastructure.
The guide’s eShopOnWeb sample is archived on GitHub (read-only). Study its structure, but do not treat it as a maintained template.
For broader interview practice, continue with architecture, design patterns, testing and security questions, including Question 203.
Sources
- Common web application architectures - .NET: Traditional layering and its testing limitations; inward dependencies; core-owned interfaces; Infrastructure implementations; DTOs; Application Core organisation and startup wiring.
- Type.GetFields Method: Reflection inspection of field types using binding flags.
- Type.GetProperties Method: Reflection inspection of declared properties.
- Type.GetMethods Method: Reflection inspection of methods and their signatures, rather than method-body dependency analysis.
- internal (C# Reference): Assembly-level accessibility of internal implementation types.
- Introduction to record types in C#: Records as data-oriented types with compiler-provided value equality.
- Migrations Overview: Plain definition of database migrations.
Practice
Checked before publishing: C# examples run on .NET 10, links opened, reviewed while it was written and read in full. How lessons are checked
Updated 1 Dec 2026 ·