Ardalis Clean Architecture Template

repository·main·Indexed 12 days ago

https://github.com/ardalis/cleanarchitecture

A production-ready starting point for implementing Clean Architecture (hexagonal, ports-and-adapters, or onion architecture) in ASP.NET Core applications. It provides scaffolding via dotnet CLI templates, including Full (clean-arch) and Minimal (min-clean) versions. The framework supports .NET 9, integrates with .NET Aspire for SQL Server orchestration, and provides guidance on Architecture Decision Records (ADR), CQRS patterns, and domain-driven design principles.

Tokens
11.8K
Snippets
31
Records
62
Agent score
96%

What's inside Ardalis Clean Architecture

  1. Compare Full vs. Minimal Clean Architecture templates

    main

    Choose your template based on project complexity and team needs:

    FeatureFull Clean Architecture (clean-arch)Minimal Clean Architecture (min-clean)
    Projects4+ (Core, UseCases, Infrastructure, Web)1 (Web only)
    OrganizationBy layer (horizontal)By feature (vertical slices)
    DDD PatternsExtensive (Aggregates, Value Objects, etc.)Pragmatic (simplified domain model)
    ComplexityHigher - more abstractionsLower - simpler structure
    Best ForLarge enterprise apps, long-term maintenanceMVPs, smaller apps, rapid iteration
    Team SizeMultiple teams, strict boundariesSmall teams, collaborative
  2. Use Domain Events to decouple operations

    main

    Domain events allow you to decouple the trigger of an operation from its implementation. This is particularly useful within domain entities because handlers can have dependencies (like services or repositories) that the entities themselves should not have.

    Workflow Example:

    1. An entity method is called (e.g., ToDoItem.MarkComplete()).
    2. The entity raises a Domain Event.
    3. A Domain Event Handler catches the event and executes the necessary side effects (e.g., sending an email or updating a different aggregate).
  3. Understand the role of the Infrastructure project

    main

    In this Clean Architecture implementation, the Infrastructure project is the dedicated layer for external concerns such as Entity Framework (EF), File systems, Email, Web Services, and Cloud providers (Azure/AWS/GCP).

    Key architectural rules:

    • Separation of Concerns: Infrastructure must keep technical implementation details separate from core business rules (Domain model).
    • Dependency Direction: Infrastructure depends on the Core (and optionally Use Cases) project. It implements the abstractions (interfaces) defined in those layers.
    • Dependency Injection: Implementations are wired up at application startup using Microsoft.Extensions.DependencyInjection via extension methods provided within this project.
  4. Understand the Clean Architecture solution structure

    main

    The template organizes code into four primary layers to maintain separation of concerns:

    • Core: Contains domain entities, value objects, and interfaces.
    • UseCases: Contains application logic and CQRS (Command Query Responsibility Segregation) handlers.
    • Infrastructure: Handles data access (e.g., EF Core) and integrations with external services.
    • Web: Contains the API endpoints, implemented using FastEndpoints.
  5. Where to implement validation in Clean Architecture

    main

    Validation should be implemented at multiple layers to ensure robustness, following the principle of defensive coding. This template suggests four primary areas for validation and enforcing business invariants:

    1. Domain Model: Uses object-oriented design (encapsulation) to ensure the model is always in a consistent state. It assumes arguments passed to it are already validated; improper values should yield exceptions rather than validation results.
    2. Use Cases / Application Project: Responsible for validating Command and Query objects. This is best implemented using a Chain of Responsibility pattern via Mediator behaviors or similar pipelines.
    3. Web Project (API Endpoints): Performs input validation on request types. This template uses the REPR pattern and the FastEndpoints library, which has built-in support for validation using FluentValidation.
    4. Infrastructure Project: While not explicitly listed as a primary validation site, it handles external resource implementations and should respect the invariants defined in the Core.
  6. Organize test projects by test type

    main

    The template organizes test projects based on the type of testing performed rather than the project being tested. The included types are:

    • Unit Tests: Testing individual components in isolation.
    • Integration Tests: Testing the interaction between components and external resources.
    • Functional Tests: A specialized form of integration testing that performs subcutaneous testing of the Web project's APIs. These tests exercise the API logic without hosting a real website or going over the network.
  7. Use .NET built-in Dependency Injection instead of Autofac

    main
    This project uses the standard .NET built-in dependency injection (DI) infrastructure rather than third-party containers like Autofac. This decision was made to simplify the codebase, reduce external dependencies, and align with standard .NET conventions. When extending the project, you should use the native .NET DI extension methods (e.g., IServiceCollection) for service registration.
  8. Understand the MinimalClean project structure

    main

    MinimalClean uses a Single Project Vertical Slice Architecture (VSA). Instead of separating by technical layers (Core, Infrastructure, Web), the code is organized by feature (slices) within a single Web project.

    src/MinimalClean.Architecture.Web/
    ├── Domain/                    # Domain entities and aggregates (e.g., CartAggregate, OrderAggregate)
    ├── Infrastructure/            # Data access and external services
    │   ├── Data/
    │   │   ├── AppDbContext.cs
    │   │   ├── Config/           # EF Core configurations
    │   │   └── Migrations/
    │   └── Email/                # Email services
    ├── Endpoints/                 # API endpoints using FastEndpoints (e.g., Cart, Order, Product)
    └── Program.cs                # Application startup

    Key Design Principles:

    • Vertical Slices: Organized by feature (Cart, Order, Product) rather than layer.
    • Domain-Driven Design: Uses proper encapsulation and business logic in entities.
    • REPR Pattern: Uses FastEndpoints for clean, testable API endpoints.
  9. Understand the project structure and responsibilities

    main

    The solution is organized into several distinct projects, each with a specific role in the Clean Architecture design:

    • Core Project: The center of the architecture. All other projects depend on it. It contains the Domain Model (Entities, Aggregates, Value Objects, Domain Events, Domain Services, Specifications, Interfaces, and sometimes DTOs).
    • Use Cases Project (Optional): Also known as the Application layer. It organizes logic using CQRS (Commands and Queries).
      • Commands: Mutate the domain and must use Repository abstractions.
      • Queries: Read-only and do not require the repository pattern; they can use query services or direct SQL.
    • Infrastructure Project: Implements interfaces defined in Core to handle external dependencies (Data access, email providers, file access, web API clients, etc.).
    • Web Project: The application entry point (ASP.NET Core). It uses FastEndpoints and the REPR pattern to organize API endpoints.
    • SharedKernel: A package used to share common elements between bounded contexts. Note: You should replace the included Ardalis.SharedKernel with your own internal package.
  10. Understand the Minimal Clean Architecture approach

    main
    The Minimal Clean Architecture template is a pragmatic, single-project implementation of Clean Architecture for ASP.NET Core. It uses Vertical Slice Architecture (VSA) to organize code by feature (e.g., Cart, Order, Product) rather than by technical layer. This reduces complexity by minimizing project boundaries and unnecessary abstractions while maintaining core principles like Dependency Inversion and Testability.
  11. Navigate the Minimal Clean Architecture project structure

    main

    The project is organized into a single Web project with the following folder structure to support vertical slices:

    • Domain/: Contains domain aggregates (e.g., CartAggregate/), entities, and optional domain events.
    • Infrastructure/: Contains data access (EF Core AppDbContext, configurations, migrations) and external services (Email, etc.).
    • Endpoints/: Contains the presentation layer, organized by feature (e.g., Cart/Create.cs).
    • Program.cs: The application startup entry point.
    MinimalClean.Architecture.Web/
    ├── Domain/                         # Domain Layer
    │   ├── CartAggregate/
    │   │   ├── Cart.cs                 # Aggregate root
    │   │   ├── CartItem.cs            # Entity
    │   │   └── Events/                # Domain events (optional)
    │   ├── OrderAggregate/
    │   └── ProductAggregate/
    ├── Infrastructure/                 # Infrastructure Layer
    │   ├── Data/
    │   │   ├── AppDbContext.cs        # EF Core DbContext
    │   │   ├── Config/                # EF configurations
    │   │   │   ├── CartConfiguration.cs
    │   │   │   └── OrderConfiguration.cs
    │   │   └── Migrations/
    │   ├── Email/
    │   └── Services/
    ├── Endpoints/                      # Presentation Layer
    │   ├── Cart/
    │   │   ├── Create.cs              # Create cart endpoint
    │   │   ├── AddItem.cs             # Add item to cart
    │   │   └── List.cs               # List carts
    │   ├── Order/
    │   └── Product/
    └── Program.cs                     # Application startup