Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 14

    Clean Architecture Solution Structure in .NET: Where Each Class Goes and When a Layer Earns Its Place

    What this lesson teaches

    Clean Architecture solution structure in .NET separates business rules from code that handles requests and code that stores data. Learn where classes belong and how to explain your choices in an interview.

    A common split uses Domain, Application, Infrastructure, and Web projects. You do not need four projects to get those boundaries. A small application can use folders, provided its code respects the same dependency direction.

    When someone asks, “Explain the architecture of your last project,” start with the problem your application solved. Then explain which boundaries mattered and what they cost. A list of project names is not enough.

    By the end, you can place a class, explain project references, spot unnecessary layers, and give a two-minute architecture answer.

    Where each class belongs

    A layer groups code with a particular responsibility. A boundary separates responsibilities so that changing one does not unnecessarily change another.

    Here is a common four-project arrangement. It is a useful starting point, not an official required layout. A contract here means an interface: a list of operations that another class promises to provide.

    ProjectResponsibilityTypical contents
    DomainExpress business rules.Orders, money, cancellation rules, business events.
    ApplicationCoordinate actions the application supports.Cancel-order handling, contracts for storage, input and result data.
    InfrastructureConnect those actions to outside systems.Database access, email delivery, vendor-specific code.
    Web/APIAccept requests and prepare responses.HTTP entry points and startup code that creates objects and connects them (wiring).

    Microsoft's guide lists entities as business model classes that are persisted, meaning saved for later use. In this layout, put the order and its cancellation rules in Domain. Add other business concepts only when the application needs them, not just to fill the project.

    The use case in the console example below is cancelling an order. Application coordinates the action: its handler loads the order and asks it to cancel. The order decides whether cancellation is allowed.

    Entity Framework Core, or EF Core, is a library for accessing databases using .NET objects. A migration records a database structure change so it can be applied later. These belong in Infrastructure, alongside email implementations.

    An endpoint is the code that handles an incoming request at a particular API address. It belongs in Web/API and should translate the request into a use-case call.

    Microsoft's architecture guide uses three main projects: Application Core, Infrastructure, and UI. Its Application Core combines responsibilities that this four-project layout separates into Domain and Application.

    Here is where the files could go with four projects:

    Text
    src/
      Domain/
        Orders/Order.cs
      Application/
        Orders/CancelOrderHandler.cs
        Orders/IOrders.cs
      Infrastructure/
        Persistence/AppDbContext.cs
        Persistence/Migrations/
      Web/
        Program.cs
        Endpoints/OrderEndpoints.cs

    For a smaller application, the same responsibilities can be folders inside one project:

    Text
    src/OrderApp/
      Domain/
        Orders/Order.cs
      Application/
        Orders/CancelOrderHandler.cs
        Orders/IOrders.cs
      Infrastructure/
        Persistence/AppDbContext.cs
        Persistence/Migrations/
      Web/
        Endpoints/OrderEndpoints.cs
      Program.cs

    In the single-project version, Program.cs contains startup code. Folders organize the code, but do not prevent one folder's code from using another's.

    The mistake to avoid. Do not describe four projects as the definition of Clean Architecture. Their responsibilities and dependency direction matter more than their names or count.

    In an interview, say: “We separated business rules, use-case coordination, external integrations, and HTTP handling. We used four projects, but a smaller application could keep those responsibilities in folders.”

    Which project references which?

    A project reference lets code in one project use code from another. Picture the projects as rings: Domain is in the centre, Application surrounds it, and Infrastructure and Web are outside. Inward means toward Domain. References for business behavior point inward, toward the rules:

    • Application references Domain.
    • Infrastructure references Application and, where needed, Domain.
    • Web references Application.
    • For this lesson's layout, keep Domain free of references to the other application projects.

    This is the four-project version of the Application Core dependency rule in Microsoft's architecture guide. In the console example below, Order uses OrderStatus, but neither uses the handler or repository.

    Web may also reference Infrastructure to assemble the application at startup. Keep that access in the composition root, the place where concrete objects are created and connected.

    flowchart TD
        W["Web/API"] -->|"calls use cases in"| A["Application"]
        W -->|"wires at startup"| I["Infrastructure"]
        I -->|"implements contracts in"| A
        A -->|"uses rules in"| D["Domain"]

    The arrows show source-code dependencies, including Web's startup-only access to Infrastructure.

    This arrangement reverses the classic N-layer direction explained in Clean Architecture in .NET: The Dependency Rule. The cost is defining those interfaces and connecting their implementations at startup.

    The console example below shows dependency injection: it creates a repository outside the handler, then supplies it through the handler's constructor. The handler does not create the repository itself. This connects the objects manually, without a dependency-injection package. Read more in the .NET dependency injection overview.

    An endpoint should not use its startup access to reach directly into database code. Otherwise, the use-case boundary is easy to bypass.

    The mistake to avoid. Do not make Application reference Infrastructure so it can create a database implementation. Supply that implementation from the composition root instead.

    In an interview, say: “Business-code dependencies point inward. Application references Domain. Infrastructure implements interfaces that Application defines. Web touches Infrastructure only in the composition root to connect implementations.”

    Where interfaces and DTOs live

    A port is an interface at the edge of the inner code. This lesson uses outgoing (driven) ports: interfaces for something the inner code needs from outside, such as loading an order. Incoming (driving) ports describe what the application offers to its callers.

    Put a port with the code that needs its promise, not automatically beside its implementation. An application-specific email sender contract usually belongs in Application. Its vendor-specific implementation belongs in Infrastructure.

    A repository provides operations for retrieving and storing business objects. Its interface can belong in Application when it serves use cases. It can belong in Domain when the contract is part of the business model. Neither location requires Domain to know EF Core.

    A Data Transfer Object, or DTO, can be a simple data class that Application services or interfaces use without depending on UI or Infrastructure.

    “DTOs at the edge” means at the relevant boundary, not necessarily all in Web:

    • An HTTP request DTO belongs at the Web boundary.
    • A use-case input or result DTO can belong in Application.
    • A vendor's response format stays in Infrastructure.

    Mapping means copying or transforming data between representations. Separate DTOs help when boundaries need different information or evolve independently. If three identical representations are copied through three layers, ask what each separation protects.

    The mistake to avoid. Do not create an interface for every class or a new DTO for every method call. Neither automatically creates a useful boundary.

    In an interview, say: “Ports live with their users, usually Application, or Domain for repositories that belong to the business model. DTOs live at the boundaries they describe.”

    See the difference: cancelling a shipped order

    The pass-through service in this example forwards CancelOrder() directly to the store.

    The rule here is simple: a shipped order cannot be cancelled.

    The first path sends the cancellation through a service and a store. The second sends it through a handler that calls Order.Cancel(). A handler is a class that coordinates one use case. Its repository is an in-memory fake: a small replacement that keeps data in memory instead of using a database.

    Guess both results before running this complete .NET 10 console program.

    C#Runs
    var unprotected = new UnprotectedOrder();
    var passThrough = new PassThroughService(new DirectOrderStore(unprotected));
    passThrough.CancelOrder();
    Console.WriteLine($"Pass-through: {unprotected.Status}");
    
    var order = new Order();
    var repository = new InMemoryOrders(order);
    var handler = new CancelOrderHandler(repository);
    var cancelled = handler.Handle();
    Console.WriteLine($"Rule protected: {(cancelled ? "cancelled" : "refused")}; {order.Status}");
    
    public enum OrderStatus { Shipped, Cancelled }
    
    public sealed class UnprotectedOrder
    {
        public OrderStatus Status { get; set; } = OrderStatus.Shipped;
    }
    
    public sealed class PassThroughService
    {
        private readonly DirectOrderStore store;
        public PassThroughService(DirectOrderStore store) => this.store = store;
        public void CancelOrder() => store.CancelOrder();
    }
    
    public sealed class DirectOrderStore
    {
        private readonly UnprotectedOrder order;
        public DirectOrderStore(UnprotectedOrder order) => this.order = order;
        public void CancelOrder() => order.Status = OrderStatus.Cancelled;
    }
    
    public sealed class Order
    {
        public OrderStatus Status { get; private set; } = OrderStatus.Shipped;
    
        public bool Cancel()
        {
            if (Status == OrderStatus.Shipped)
                return false;
    
            Status = OrderStatus.Cancelled;
            return true;
        }
    }
    
    public interface IOrders
    {
        Order Load();
    }
    
    public sealed class CancelOrderHandler
    {
        private readonly IOrders orders;
        public CancelOrderHandler(IOrders orders) => this.orders = orders;
        public bool Handle() => orders.Load().Cancel();
    }
    
    public sealed class InMemoryOrders : IOrders
    {
        private readonly Order order;
        public InMemoryOrders(Order order) => this.order = order;
        public Order Load() => order;
    }
    Output
    Pass-through: Cancelled
    Rule protected: refused; Shipped

    The first four lines create a shipped order and send cancellation through two classes. Neither checks the rule. The output therefore says Pass-through: Cancelled. Two forwarding classes looked layered but protected nothing.

    The next three lines create the order, the fake repository, and the handler. These lines act as the composition root. Then we call Handle() and print the result.

    Handle() loads the order and calls Cancel(). That method sees Shipped, returns false, and leaves the status unchanged. The second line says Rule protected: refused; Shipped.

    In separate projects, Order and OrderStatus would belong in Domain. CancelOrderHandler and this use-case-specific IOrders would belong in Application. The fake could live in a test project; a database implementation would live in Infrastructure.

    The handler is short, but its purpose differs from the first service. It runs the use case through an interface that Application owns, and it lets the order make the decision. Even so, do not add further forwarding classes around it without a reason.

    The mistake to avoid. Do not count forwarding calls as rule protection. The protected version works because cancellation goes through a method that enforces the rule, not because it has more classes.

    In an interview, say: “A pass-through service adds an extra hop (indirection): one more class the call goes through, without protecting a rule. It means more files to follow and edit per feature. I keep a handler when it provides useful coordination or a boundary we actually use.”

    When a layer earns its place

    For a small CRUD application—one mainly creating, reading, updating, and deleting records—four projects are often unnecessary. Start with a simple structure and add boundaries when there is something worth protecting.

    A layer earns its cost when it does at least one useful job:

    • It protects a business rule, as Order.Cancel() does.
    • It hides a vendor likely to change, such as an email provider.
    • It provides a test seam, a place where a test can substitute a collaborator.
    • It supports a real second implementation, rather than an imagined future one.

    Folders are cheaper to introduce, but they rely on discipline. Separate projects make some unwanted references harder to introduce. They also add navigation, setup, and maintenance work.

    A generic repository that only renames database-library calls adds no useful contract; The Repository Pattern With EF Core explains when one helps and when it hurts.

    Other warning signs are pass-through services, an interface per class, and one DTO mapped three times without changing meaning. Over-engineering means adding structure whose ongoing cost exceeds the problem it solves.

    For another perspective, read when not to use design patterns. For practical wiring, continue with testable seams and the composition root.

    The mistake to avoid. Do not defend a layer only because a template included it. Name the rule, change, or test that justifies its cost.

    In an interview, say: “Yes, this can be overkill for a CRUD app. I start simple and add a boundary when a business rule, changing vendor, or useful test seam needs it.”

    Build your two-minute architecture answer

    Use five parts: context, boundaries, dependency direction, one trade-off, and one change you would make.

    Here is an illustrative answer. Replace it with facts from your own work:

    In an interview, say: “We built an order-management API. The important rules covered cancellation and shipping. Domain owned those rules, Application coordinated use cases, Infrastructure handled the database and email, and Web handled HTTP. Dependencies pointed inward, with startup wiring in Web. We chose separate projects to keep database code out of the rules. The cost was more files and mapping for simple features. If I changed it now, I would remove forwarding services that add no behavior, while keeping the boundaries around order rules.”

    Be ready to name one actual class and follow a request through it. Explain a real difficulty rather than claiming the structure made every change easy.

    The mistake to avoid. Do not present this sample as personal experience. An honest account of a smaller system is stronger than a polished architecture you cannot explain.

    Check yourself

    In this lesson's four-project layout, where does CreateOrderRequest, the shape of an incoming HTTP request, belong?

    A Domain
    B Application
    C Web
    D Infrastructure
    Show answer

    Correct answer: C

    An HTTP request DTO belongs at the Web boundary. The endpoint translates it into a use-case call.

    Option A: Domain holds business rules, not the shape of HTTP requests.

    Option B: Application can own a use-case input DTO, but not the HTTP request format.

    Option D: Infrastructure holds outside integrations such as database access and email delivery.

    In the same layout, where does OrderConfiguration, the EF Core mapping for orders, belong?

    A Domain
    B Application
    C Infrastructure
    D Web
    Show answer

    Correct answer: C

    EF Core mapping is database-specific code. It belongs in Infrastructure with the DbContext and migrations.

    Option A: Domain holds business rules and must not need EF Core to compile.

    Option B: Application coordinates use cases and owns the contracts they need, not database mapping.

    Option D: Web may wire Infrastructure at startup, but mapping code does not belong there.

    A small CRUD application has no special business rules, one database, and several services that only forward calls. What is the best next step?

    A Add a separate project for each service so its boundary is enforced.
    B Keep the structure simple and add a boundary only for a clear reason.
    C Add an interface for every class so that each one can be replaced later.
    D Map each DTO into a new DTO at every layer so changes stay isolated.
    Show answer

    Correct answer: B

    Boundaries have a cost. Add them when they protect rules, isolate change, or provide a test seam you use.

    An Application handler needs to load an order. Where should its storage contract and database implementation usually go?

    A The contract in Application and the implementation in Infrastructure.
    B The contract in Infrastructure and the implementation in Application.
    C Both in Web, because requests start there.
    D Both in Domain, including EF Core database code.
    Show answer

    Correct answer: A

    Application owns the operation it needs. Infrastructure supplies the implementation without making Application depend on database code.

    Going deeper

    The example deliberately handles one existing order and has no database. A production use case also needs decisions about missing orders, saving changes, and competing updates. A fake proves the cancellation behavior here; it does not prove database behavior.

    Templates are starting points, not architecture requirements. As read on 1 Dec 2026:

    Check every package a template brings, and its licence, before adopting it. The console example demonstrates the dependency direction without a template or additional packages.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    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 ·