## 1. Project Overview & Quickstart (ardalis/CleanArchitecture)

## File: README.md

[](https://github.com/ardalis/CleanArchitecture/actions)
[](https://github.com/ardalis/CleanArchitecture/actions/workflows/publish.yml)
[](https://www.nuget.org/packages/Ardalis.CleanArchitecture.Template/)

<a href="https://twitter.com/intent/follow?screen_name=ardalis">
    
</a> &nbsp; <a href="https://twitter.com/intent/follow?screen_name=nimblepros">
    
</a>







# Clean Architecture

A starting point for Clean Architecture with ASP.NET Core. [Clean Architecture](https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html) is just the latest in a series of names for the same loosely-coupled, dependency-inverted architecture. You will also find it named [hexagonal](https://alistair.cockburn.us/hexagonal-architecture), [ports-and-adapters](http://www.dossier-andreas.net/software_architecture/ports_and_adapters.html), or [onion architecture](http://jeffreypalermo.com/blog/the-onion-architecture-part-1/).

Learn more about Clean Architecture and this template in [NimblePros' Introducing Clean Architecture course](https://academy.nimblepros.com/p/learn-clean-architecture). Use code ARDALIS to save 20%.

This architecture is used in the [DDD Fundamentals course](https://www.pluralsight.com/courses/fundamentals-domain-driven-design) by [Steve Smith](https://ardalis.com) and [Julie Lerman](https://thedatafarm.com/).

:school: Contact Steve's company, [NimblePros](https://nimblepros.com/), for Clean Architecture or DDD training and/or implementation assistance for your team.

## Take the Course!

[Learn about how to implement Clean Architecture](https://academy.nimblepros.com/p/intro-to-clean-architecture) from [NimblePros](https://nimblepros.com) trainers [Sarah "sadukie" Dutkiewicz](https://blog.nimblepros.com/author/sadukie/) and [Steve "ardalis" Smith](https://blog.nimblepros.com/author/ardalis/).

## Table Of Contents

- [Clean Architecture](#clean-architecture)
  - [Take the Course!](#take-the-course)
  - [Table Of Contents](#table-of-contents)
  - [Give a Star! :star:](#give-a-star-star)
  - [Sponsors](#sponsors)
  - [Troubleshooting Chrome Errors](#troubleshooting-chrome-errors)
  - [Versions](#versions)
  - [Learn More](#learn-more)
- [Getting Started](#getting-started)
  - [Template Installation](#template-installation)
  - [Using the dotnet CLI template](#using-the-dotnet-cli-template)
    - [Full Clean Architecture (`clean-arch`)](#full-clean-architecture-clean-arch)
    - [Minimal Clean Architecture (`min-clean`)](#minimal-clean-architecture-min-clean)
  - [Template Comparison](#template-comparison)
    - [Which Template Should I Use?](#which-template-should-i-use)
  - [What about Controllers and Razor Pages?](#what-about-controllers-and-razor-pages)
    - [Add Ardalis.ApiEndpoints](#add-ardalisapiendpoints)
    - [Add Controllers](#add-controllers)
    - [Add Razor Pages](#add-razor-pages)
  - [Using the GitHub Repository](#using-the-github-repository)
  - [Running Migrations](#running-migrations)
- [Goals](#goals)
  - [History and Shameless Plug Section](#history-and-shameless-plug-section)
- [Design Decisions and Dependencies](#design-decisions-and-dependencies)
  - [Where To Validate](#where-to-validate)
  - [The Core Project](#the-core-project)
  - [The Use Cases Project](#the-use-cases-project)
  - [The Infrastructure Project](#the-infrastructure-project)
  - [The Web Project](#the-web-project)
  - [The SharedKernel Package](#the-sharedkernel-package)
  - [The Test Projects](#the-test-projects)
- [Patterns Used](#patterns-used)
  - [Domain Events](#domain-events)
  - [Related Projects](#related-projects)
  - [Presentations and Videos on Clean Architecture](#presentations-and-videos-on-clean-architecture)

## Give a Star! :star:

If you like or are using this project to learn or start your solution, please give it a star. Thanks!

Or if you're feeling really generous, we now support GitHub sponsorships - see the button above.

## Sponsors

I'm please to announce that [Amazon AWS's FOSS fund](https://github.com/aws/dotnet-foss) has chosen to award a 12-month sponsorship to this project. Thank you, and thanks to all of my other past and current sponsors!

## Troubleshooting Chrome Errors

By default the site uses HTTPS and expects you to have a self-signed developer certificate for localhost use. If you get an error with Chrome [see this answer](https://stackoverflow.com/a/31900210/13729) for mitigation instructions.

## Versions

The main branch is now using **.NET 9**. This corresponds with NuGet package version 10.x. Previous versions are available - see our [Releases](https://github.com/ardalis/CleanArchitecture/releases).

## Learn More

- [Live Stream Recordings Working on Clean Architecture](https://www.youtube.com/c/Ardalis/search?query=clean%20architecture)
- [DotNetRocks Podcast Discussion with Steve "ardalis" Smith](https://player.fm/series/net-rocks/clean-architecture-with-steve-smith)
- [Fritz and Friends Streaming Discussion with Steve "ardalis" Smith](https://www.youtube.com/watch?v=k8cZUW4MS3I)

# Documentation

The official documentation for this template, including Getting Started steps, Migration Guides, and Architectural Decisions, can be found at [Ardalis Clean Architecture Docs](https://ardalis.github.io/CleanArchitecture).

If you are upgrading from an older version, please be sure to review our [Migration Guides](https://ardalis.github.io/CleanArchitecture/migration-guides/) on the new documentation site!

---

## File: docs/content/architecture-decisions/_index.md

---
title: "Architecture Decisions"
weight: 40
---

# Architecture Decisions

Records of significant architectural decisions made in this template.

---

## File: docs/content/architecture-decisions/adr-001-dotnet-di-adoption.md

---
title: "ADR 001: Replace Autofac with .NET DI"
weight: 10
---

# ADR 001: Replace Autofac with .NET Core Dependency Injection

## Status
Accepted

## Context
Initially, this repository employed Autofac for dependency injection. At the time of adoption, Autofac was preferred due to its robust feature set, including:
- Support for advanced scenarios such as decorators and modules, which could be placed close to their corresponding implementations.
- A well-established history of stability and maturity, having been used in various projects before .NET Core's built-in DI was fully featured.

As the .NET ecosystem evolved, the built-in DI container began to meet the needs of our project without introducing the added complexity associated with Autofac. The .NET DI framework has matured significantly, offering sufficient functionality for typical use cases, including:
- Improved support for configuration through extension methods.
- A simpler learning curve for new contributors familiar with .NET conventions.

## Decision
Based on community feedback and a review of our project's requirements, we have decided to remove Autofac from this template and transition to using .NET's built-in dependency injection infrastructure. This decision aligns with the goal of simplifying the codebase and reducing external dependencies.

## Consequences
- **Simplified Codebase**: Removing Autofac results in a cleaner, more maintainable codebase that adheres to .NET standards.
- **Reduced Complexity**: The transition eliminates the need for additional files and configurations specific to Autofac, making the project easier to understand for new contributors.
- **Standardization**: Adopting .NET's built-in DI promotes consistency with other .NET projects, making it easier for developers familiar with the framework to contribute effectively.

## References
- [Issue #649: Why is this repo using Autofac instead of .NET's own DI infrastructure?](https://github.com/ardalis/CleanArchitecture/issues/649) - Discussion that led to this decision.
- [Getting Started with Architecture Decision Records](https://ardalis.com/getting-started-with-architecture-decision-records/) - Resource on ADR best practices.

---

## File: docs/content/architecture-decisions/README.md

# Architecture Decision Records (ADR)

## What is an Architecture Decision Record (ADR)?
An Architecture Decision Record (ADR) documents significant architecture decisions made throughout a project, capturing the context, rationale, and consequences of each decision. This promotes transparency and provides a historical reference for future design considerations.

## Purpose of ADRs
- **Knowledge Management**: Consolidates architectural knowledge and decisions.
- **Collaboration**: Enhances team communication by documenting discussions and outcomes.
- **Clarity**: Provides clear reasoning behind design choices, making it easier for new team members to understand past decisions.

## Best Practices for Writing ADRs
1. **Be Specific**: Each ADR should address a single architectural decision. Avoid conflating multiple decisions into one record.
2. **Document Context**: Clearly explain the project’s context and relevant considerations that influenced the decision. Include team dynamics and priorities.
3. **Rationale and Consequences**: Describe the reasons for the decision, including pros and cons, and outline the implications of the decision for the project and 

future architecture.
4. **Immutable Records**: Once an ADR is created, avoid altering it. Instead, create a new ADR to reflect any changes or updates.
5. **Timestamp Entries**: Include timestamps to track when each decision was made, especially for aspects that may evolve over time (e.g., costs, schedules).
6. **Use Templates**: Utilize established templates for consistency and completeness in documenting ADRs.

## Versioning ADRs
- **Track Changes**: Each time an ADR is updated or a new version is created, increment the version number (e.g., `v1.0`, `v1.1`, etc.) to reflect changes clearly.
- **Document Changes**: Include a "Changelog" section in the ADR to summarize what has changed in each version. This can include updates to the rationale, context, or decision consequences.
- **Maintain Clarity**: Ensure the latest version is easily accessible while keeping older versions for reference. You might consider using a version control system (e.g., Git) to manage this effectively.

## How to Start Using ADRs
1. **Identify Decisions**: Collaborate with your team to identify significant architecture decisions that need documentation.
2. **Select a Tool**: Choose a tool for documenting ADRs (e.g., markdown files in a Git repository, Google Docs, project management tools).
3. **Create ADRs**: For each decision, create an ADR file in the `adr` directory, following naming conventions (e.g., `choose-database.md`).

## File Name Conventions
- Use a present tense imperative verb phrase.
- Separate words with lowercase letters and dashes.
- Use `.md` extension for markdown formatting.

## Templates
Refer to the following templates for structuring your ADRs:
- [Decision record template by Michael Nygard](https://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions)
- [Decision record template by Jeff Tyree and Art Akerman](https://github.com/adr/adr)
- [MADR project templates](https://adr.github.io/madr/)

## Teamwork Advice for ADRs
- Foster a culture of collaborative decision-making and ensure ADRs are seen as valuable tools rather than bureaucratic requirements.
- Consider using the term "decisions" instead of "ADRs" to encourage engagement.
- Maintain living documents by updating existing ADRs with new information rather than rewriting them.

## For More Information
- [Architectural Decision Wikipedia](https://en.wikipedia.org/wiki/Architectural_decision)
- [Markdown Architectural Decision Records](https://adr.github.io/)
- [Tools for working with ADRs](https://github.com/adr/adr)

By following these guidelines, your team can effectively leverage ADRs to enhance architectural decision-making and project transparency while keeping a clear version history of all architectural decisions.

---

## File: docs/content/migration-guides/_index.md

---
title: "Migration Guides"
weight: 50
---

# Migration Guides

Because this template is primarily intended as a **starting point** rather than a continuously updated library (like a NuGet package), there is no automated upgrade path for existing applications. 

However, these guides outline the major changes between versions and provide the recommended upgrade strategy for projects that want to adopt the latest architectural patterns.

---

## File: docs/content/migration-guides/v10-to-v11.md

---
title: "Upgrading from v10.x to v11.x"
weight: 1
---

# Upgrading from v10.x to v11.x

If you started your project with version `10.0.1` (or similar) of the template and want to incorporate the architectural upgrades of version `11.0.0`, follow this guide.

## The "Diff" Strategy

Since this template serves as a starting point, the most reliable way to upgrade an existing project is to perform a differential comparison:

1. Generate a **brand new solution** using the `v11` template (e.g., `dotnet new clean-arch -o Your.ProjectName`).
2. Use a diff tool (like Beyond Compare, WinMerge, or `git diff`) to compare the newly generated solution against the original `v10` vanilla template you started with (or your current codebase).
3. Manually apply the structural or package changes to your existing project.

## Key Changes in v11.x

Several dependencies and implementation details were altered in this release. The most significant changes include:

### 1. MediatR Replacement
One of the most noticeable changes in recent versions is the removal of the `MediatR` library for handling commands and queries inside the `UseCases` project, favoring alternative implementations or source generators (due to licensing/commercial changes). 
*   **Action Required**: Review how `ICommand`, `IQuery`, and their respective handlers (`ICommandHandler`, `IQueryHandler`) are defined in the new template. You will need to update your existing Use Case handlers to align with the new library's interfaces and base types.

### 2. FastEndpoints API Layer
Continue leveraging [FastEndpoints](https://fast-endpoints.com/) for the API layer (the REPR pattern).
*   **Action Required**: Check the `/src/Clean.Architecture.Web/Endpoints` folder in the new template to see if any base class signatures (`Endpoint`) or FluentValidation extensions have shifted.

### 3. Template Configuration & Packages
Compare the `Directory.Packages.props` file to see the newly pinned versions for Entity Framework Core, Serilog, FastEndpoints, and testing packages.
*   **Action Required**: Update your Central Package Management file accordingly to resolve any vulnerability or compatibility warnings.

---

## File: docs/content/_index.md

---
title: "Clean Architecture docs"
type: "docs"
---

# Ardalis Clean Architecture

A starting point for Clean Architecture with ASP.NET Core. Clean Architecture is just the latest in a series of names for the same loosely-coupled, dependency-inverted architecture. You will also find it named hexagonal, ports-and-adapters, or onion architecture.

Learn more about Clean Architecture and this template in [NimblePros' Introducing Clean Architecture course](https://academy.nimblepros.com/p/learn-clean-architecture). Use code ARDALIS to save 20%.

This architecture is used in the **DDD Fundamentals course** by Steve Smith and Julie Lerman.

## Give a Star! :star:

If you like or are using this project to learn or start your solution, please give it a star. Thanks!

Or if you're feeling really generous, we now support GitHub sponsorships.

## Getting Started

To use this template, there are **two template options**:

1. **Full Clean Architecture** (`clean-arch`) - Complete multi-project solution with Core, UseCases, Infrastructure, and Web
2. **Minimal Clean Architecture** (`min-clean`) - Simplified single-project vertical slice architecture

Choose based on your project's complexity and team preferences. Navigate to the sidebar on the left for detailed guidance on setup, patterns, and architectural decisions.

---

## File: docs/content/design-decisions.md

---
title: "Goals & Design Decisions"
weight: 20
---

# Goals

The goal of this repository is to provide a basic solution structure that can be used to build Domain-Driven Design (DDD)-based or simply well-factored, SOLID applications using .NET Core. Learn more about these topics here:

- [SOLID Principles for C# Developers](https://www.pluralsight.com/courses/csharp-solid-principles)
- [Domain-Driven Design Fundamentals](https://www.pluralsight.com/courses/fundamentals-domain-driven-design)
- [Refactoring to SOLID C# Code](https://www.pluralsight.com/courses/refactoring-solid-c-sharp-code)

If you're used to building applications as single-project or as a set of projects that follow the traditional UI -> Business Layer -> Data Access Layer "N-Tier" architecture, I recommend you check out these two courses (ideally before DDD Fundamentals):

- [Creating N-Tier Applications in C#, Part 1](https://www.pluralsight.com/courses/n-tier-apps-part1)
- [Creating N-Tier Applications in C#, Part 2](https://www.pluralsight.com/courses/n-tier-csharp-part2)

Steve Smith also maintains Microsoft's reference application, eShopOnWeb, and its associated free eBook. Check them out here:

- [eShopOnWeb on GitHub](https://github.com/nimblepros/eShopOnWeb) (now supported by [NimblePros](https://nimblepros.com))
- [Architecting Modern Web Applications with ASP.NET Core and Microsoft Azure](https://aka.ms/webappebook) (eBook)

Note that the goal of this project and repository is **not** to provide a sample or reference application. It's meant to just be a template, but with enough pieces in place to show you where things belong as you set up your actual solution. Instead of useless "Class1.cs" there are a few real classes in place. Delete them as soon as you understand why they're there and where you should put your own, similar files. There *is* a sample application in the `/sample` folder, if you're looking for that.

## History and Shameless Plug Section

I've used this starter kit to teach the basics of ASP.NET Core using Domain-Driven Design concepts and patterns for some time now (starting when ASP.NET Core was still in pre-release). Typically I teach a one- or two-day hands-on workshop ahead of events like DevIntersection, or private on-site workshops for companies looking to bring their teams up to speed with the latest development technologies and techniques. Feel free to [contact me](https://nimblepros.com/) if you'd like information about upcoming workshops.

# Design Decisions and Dependencies

The goal of this solution template is to provide a fairly bare-bones starter kit for new projects. It does not include every possible framework, tool, or feature that a particular enterprise application might benefit from. Its choices of technology for things like data access are rooted in what is the most common, accessible technology for most business software developers using Microsoft's technology stack. It doesn't (currently) include extensive support for things like logging, monitoring, or analytics, though these can all be added easily. Below is a list of the technology dependencies it includes, and why they were chosen. Most of these can easily be swapped out for your technology of choice, since the nature of this architecture is to support modularity and encapsulation.

## Where To Validate

Validation of user input is a requirement of all software applications. The question is, where does it make sense to implement it in a concise and elegant manner? This solution template includes 4 separate projects, each of which might be responsible for performing validation as well as enforcing business invariants (which, given validation should already have occurred, are usually modeled as exceptions).

- [When to Validate and When to Throw Exceptions](https://www.youtube.com/watch?v=dpPcnAT7n7M)

The domain model itself should generally rely on object-oriented design to ensure it is always in a consistent state. It leverages encapsulation and limits public state mutation access to achieve this, and it assumes that any arguments passed to it have already been validated, so null or other improper values yield exceptions, not validation results, in most cases.

The use cases / application project includes the set of all commands and queries the system supports. It's frequently responsible for validating its own command and query objects. This is most easily done using a [chain of responsibility pattern](https://deviq.com/design-patterns/chain-of-responsibility-pattern) via Mediator behaviors or some other pipeline.

The Web project includes all API endpoints, which include their own request and response types, following the [REPR pattern](https://deviq.com/design-patterns/repr-design-pattern). The FastEndpoints library includes built-in support for validation using FluentValidation on the request types. This is a natural place to perform input validation as well.

Having validation occur both within the API endpoints and then again at the use case level may be considered redundant. There are tradeoffs to adding essentially the same validation in two places, one for API requests and another for messages sent to Use Case handlers. Following defensive coding, it often makes sense to add validation in both places, as the overhead is minimal and the peace of mind of mind and greater application robustness is often worth it.

## The Core Project

The Core project is the center of the Clean Architecture design, and all other project dependencies should point toward it. As such, it has very few external dependencies. The Core project should include the Domain Model including things like:

- Entities
- Aggregates
- Value Objects
- Domain Events
- Domain Event Handlers
- Domain Services
- Specifications
- Interfaces
- DTOs (sometimes)

You can learn more about these patterns and how to apply them here:

- [DDD Fundamentals](https://www.pluralsight.com/courses/fundamentals-domain-driven-design)
- [DDD Concepts](https://deviq.com/domain-driven-design/ddd-overview)

## The Use Cases Project

An optional project, I've included it because many folks were demanding it and it's easier to remove than to add later. This is also often referred to as the *Application* or *Application Services* layer. The Use Cases project is organized following CQRS into Commands and Queries (I considered having folders for `Commands` and `Queries` but felt it added little - the folders per actual *command* or *query* is sufficient without extra nesting). Commands mutate the domain model and thus should always use Repository abstractions for their data access (Repositories are how one fetches and persists domain model types). Queries are readonly, and thus **do not need to use the repository pattern**, but instead can use whatever query service or approach is most convenient.

Since the Use Cases project is set up to depend on Core and does not depend on Infrastructure, there will still need to be abstractions defined for its data access. And it *can* use things like specifications, which can sometimes help encapsulate query logic as well as result type mapping. But it doesn't *have* to use repository/specification - it can just issue a SQL query or call a stored procedure if that's the most efficient way to get the data.

Although this is an optional project to include (without it, your API endpoints would just work directly with the domain model or query services), it does provide a nice UI-ignorant place to add automated tests, and lends itself toward applying policies for cross-cutting concerns using a Chain of Responsibility pattern around the message handlers (for things like validation, caching, auth, logging, timing, etc.). The template includes an example of this for logging, which is located in the [SharedKernel NuGet package](https://github.com/ardalis/Ardalis.SharedKernel/blob/main/src/Ardalis.SharedKernel/LoggingBehavior.cs).

## The Infrastructure Project

Most of your application's dependencies on external resources should be implemented in classes defined in the Infrastructure project. These classes should implement interfaces defined in Core. If you have a very large project with many dependencies, it may make sense to have multiple Infrastructure projects (e.g. Infrastructure.Data), but for most projects one Infrastructure project with folders works fine. The template includes data access and domain event implementations, but you would also add things like email providers, file access, web api clients, etc. to this project so they're not adding coupling to your Core or UI projects.

## The Web Project

The entry point of the application is the ASP.NET Core web project (or possibly the AspireHost project, which in turn loads the Web project). This is actually a console application, with a `public static void Main` method in `Program.cs`. It leverages FastEndpoints and the REPR pattern to organize its API endpoints.

## The SharedKernel Package

A [Shared Kernel](https://deviq.com/domain-driven-design/shared-kernel) is used to share common elements between bounded contexts. It's a DDD term but many organizations leverage "common" projects or packages for things that are useful to share between several applications.

I recommend creating a separate SharedKernel project and solution if you will require sharing code between multiple [bounded contexts](https://ardalis.com/encapsulation-boundaries-large-and-small/) (see [DDD Fundamentals](https://www.pluralsight.com/courses/domain-driven-design-fundamentals)). I further recommend this be published as a NuGet package (most likely privately within your organization) and referenced as a NuGet dependency by those projects that require it.

Previously a project for SharedKernel was included in this project. However, for the above reasons I've made it a separate package, [Ardalis.SharedKernel](https://github.com/ardalis/Ardalis.SharedKernel), which **you should replace with your own when you use this template**.

If you want to see another [example of a SharedKernel package, the one I use in my updated Pluralsight DDD course is on NuGet here](https://www.nuget.org/packages/PluralsightDdd.SharedKernel/).

## The Test Projects

Test projects could be organized based on the kind of test (unit, functional, integration, performance, etc.) or by the project they are testing (Core, Infrastructure, Web), or both. For this simple starter kit, the test projects are organized based on the kind of test, with unit, functional and integration test projects existing in this solution. Functional tests are a special kind of [integration test](https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-8.0) that perform [subcutaneous testing](https://martinfowler.com/bliki/SubcutaneousTest.html) of the APIs of the Web project, without actually hosting a real website or going over the network. I've created a bunch of [test helpers](https://github.com/ardalis/HttpClientTestExtensions) to make these kinds of tests shorter and easier to maintain.

# Patterns Used

This solution template has code built in to support a few common patterns, especially Domain-Driven Design patterns. Here is a brief overview of how a few of them work.

## Domain Events

Domain events are a great pattern for decoupling a trigger for an operation from its implementation. This is especially useful from within domain entities since the handlers of the events can have dependencies while the entities themselves typically do not. In the sample, you can see this in action with the `ToDoItem.MarkComplete()` method. The following sequence diagram demonstrates how the event and its handler are used when an item is marked complete through a web API endpoint.



## Related Projects

- [ApiEndpoints](https://github.com/ardalis/apiendpoints)
- [GuardClauses](https://github.com/ardalis/guardclauses)
- [HttpClientTestExtensions](https://github.com/ardalis/HttpClientTestExtensions)
- [Result](https://github.com/ardalis/result)
- [SharedKernel](https://github.com/ardalis/Ardalis.SharedKernel)
- [SmartEnum](https://github.com/ardalis/SmartEnum)
- [Specification](https://github.com/ardalis/specification)
- [FastEndpoints](https://fast-endpoints.com/)

## Presentations and Videos on Clean Architecture

- [What's New in Clean Architecture Template 9.1](https://www.youtube.com/watch?v=EJIgjL41em4)
- [The REPR Pattern and Clean Architecture](https://www.youtube.com/watch?v=-AJcEJPwagQ)
- [Clean Architecture with ASP.NET Core 8](https://www.youtube.com/watch?v=yF9SwL0p0Y0)
- [Getting Started with Clean Architecture and .NET 8 (webinar)](https://www.youtube.com/watch?v=IsmyqNrfQQw)

---

## File: docs/content/getting-started.md

---
title: "Getting Started"
weight: 10
---

# Getting Started

To use this template, there are **two template options**:

1. **Full Clean Architecture** (`clean-arch`) - Complete multi-project solution with Core, UseCases, Infrastructure, and Web
2. **Minimal Clean Architecture** (`min-clean`) - Simplified single-project vertical slice architecture

Choose based on your project's complexity and team preferences. See [Template Comparison](#template-comparison) below.

## Template Installation

Install the templates from NuGet:

```powershell
# Full Clean Architecture template
dotnet new install Ardalis.CleanArchitecture.Template

# Minimal Clean Architecture template  
dotnet new install Ardalis.MinimalClean.Template
```

## Using the dotnet CLI template

### Full Clean Architecture (`clean-arch`)

First, install the template from [NuGet (https://www.nuget.org/packages/Ardalis.CleanArchitecture.Template/)](https://www.nuget.org/packages/Ardalis.CleanArchitecture.Template/):

```powershell
dotnet new install Ardalis.CleanArchitecture.Template
```

You can see available options by running the command with the `-?` option:

```powershell
dotnet new clean-arch -?
ASP.NET Clean Architecture Solution (C#)
Author: Steve Smith @ardalis, Erik Dahl

Usage:
  dotnet new clean-arch [options] [template options]

Options:
  -n, --name <name>       The name for the output being created. If no name is specified, the name of the output
                          directory is used.
  -o, --output <output>   Location to place the generated output.
  --dry-run               Displays a summary of what would happen if the given command line were run if it would result
                          in a template creation.
  --force                 Forces content to be generated even if it would change existing files.
  --no-update-check       Disables checking for the template package updates when instantiating a template.
  --project      The project that should be used for context evaluation.
  -lang, --language <C#>  Specifies the template language to instantiate.
  --type         Specifies the template type to instantiate.

Template options:
  -as, --aspire  Include .NET Aspire.
                 Type: bool
                 Default: false
```

You should see the template in the list of templates from `dotnet new list` after this installs successfully. Look for "ASP.NET Clean Architecture Solution" with Short Name of "clean-arch".

Navigate to the parent directory in which you'd like the solution's folder to be created.

Run this command to create the solution structure in a subfolder name `Your.ProjectName`:

```powershell
dotnet new clean-arch -o Your.ProjectName
```

The `Your.ProjectName` directory and solution file will be created, and inside that will be all of your new solution contents, properly namespaced and ready to run/test!

Thanks [@dahlsailrunner](https://github.com/dahlsailrunner) for your help getting this working!

**Known Issues**:

- Don't include hyphens in the name. See [#201](https://github.com/ardalis/CleanArchitecture/issues/201).
- Don't use 'Ardalis' as your namespace (conflicts with dependencies).

### Minimal Clean Architecture (`min-clean`)

For a simpler, single-project vertical slice architecture, use the Minimal Clean Architecture template:

```powershell
dotnet new install Ardalis.MinimalClean.Template
dotnet new min-clean -o Your.ProjectName
```

This template provides:

- **Single Web project** with all code organized by vertical slices (features)
- **Simplified architecture** - no separate Core, UseCases, or Infrastructure projects
- **Domain-Driven Design patterns** - entities, aggregates, but pragmatic
- **FastEndpoints** for clean API endpoints
- **Entity Framework Core** with migrations
- **Aspire** support for cloud-ready development (optional)

Perfect for MVPs, smaller applications, or teams that want architectural guidance without multi-project complexity.

## Template Comparison

| Feature | Full Clean Architecture | Minimal Clean Architecture |
|---------|------------------------|----------------------------|
| **Command** | `clean-arch` | `min-clean` |
| **Projects** | 4+ (Core, UseCases, Infrastructure, Web) | 1 (Web only) |
| **Organization** | By layer (horizontal) | By feature (vertical slices) |
| **DDD Patterns** | Extensive (Aggregates, Value Objects, Domain Events, Specifications) | Pragmatic (simplified domain model) |
| **Repository Pattern** | Yes, with Specifications | Optional (direct DbContext or simple repos) |
| **Mediator/CQRS** | Yes (separate UseCases project) | Optional (can be in endpoints) |
| **Complexity** | Higher - more abstractions | Lower - simpler structure |
| **Best For** | Large enterprise apps, long-term maintenance | MVPs, smaller apps, rapid iteration |
| **Team Size** | Multiple teams, strict boundaries | Small teams, collaborative |
| **Learning Curve** | Steeper - more patterns to learn | Gentler - focused essentials |
| **Migration Path** | Can simplify to minimal | Can grow into full template |

### Which Template Should I Use?

**Choose Full Clean Architecture if:**

- Building large, complex enterprise applications
- Multiple teams working on different layers
- Long-term maintenance and evolution expected
- Need strict separation of concerns and testability
- Domain complexity requires extensive DDD patterns

**Choose Minimal Clean Architecture if:**

- Building MVPs or smaller applications
- Want architectural guidance without project overhead
- Prefer vertical slice architecture
- Team values simplicity and fast iteration
- May grow into full Clean Architecture later

**Not sure?** Start with Minimal Clean and migrate to Full Clean Architecture if your application grows in complexity.

## What about Controllers and Razor Pages?

As of version 9, this solution template only includes support for API Endpoints using the FastEndpoints library. If you want to use my ApiEndpoints library, Razor Pages, and/or Controllers you can use the last template that included them, [version 7.1](https://www.nuget.org/packages/Ardalis.CleanArchitecture.Template/7.1.0). Alternately, they're easily added to this template after installation.

### Add Ardalis.ApiEndpoints

To use [Ardalis.ApiEndpoints](https://www.nuget.org/packages/Ardalis.ApiEndpoints) instead of (or in addition to) [FastEndpoints](https://fast-endpoints.com/), just add the reference and use the base classes from the documentation.

```powershell
dotnet add package Ardalis.ApiEndpoints
```

### Add Controllers

You'll need to add support for controllers to the Program.cs file. You need:

```csharp
builder.Services.AddControllers(); // ControllersWithView if you need Views

// and

app.MapControllers();
```

Once these are in place, you should be able to create a Controllers folder and (optionally) a Views folder and everything should work as expected. Personally I find Razor Pages to be much better than Controllers and Views so if you haven't fully investigated Razor Pages you might want to do so right about now before you choose Views.

### Add Razor Pages

You'll need to add support for Razor Pages to the Program.cs file. You need:

```csharp
builder.Services.AddRazorPages();

// and

app.MapRazorPages();
```

Then you just add a Pages folder in the root of the project and go from there.

## Using the GitHub Repository

To get started based on this repository, you need to get a copy locally. You have three options: fork, clone, or download. Most of the time, you probably just want to download.

You should **download the repository**, unblock the zip file, and extract it to a new folder if you just want to play with the project or you wish to use it as the starting point for an application.

You should **fork this repository** only if you plan on submitting a pull request. Or if you'd like to keep a copy of a snapshot of the repository in your own GitHub account.

You should **clone this repository** if you're one of the contributors and you have commit access to it. Otherwise you probably want one of the other options.

## Running Migrations

You shouldn't need to do this to use this template, but if you want migrations set up properly in the Infrastructure project, you need to specify that project name when you run the migrations command.

In Visual Studio, open the Package Manager Console, and run `Add-Migration InitialMigrationName -StartupProject Your.ProjectName.Web -Context AppDbContext -Project Your.ProjectName.Infrastructure`.

In a terminal with the CLI, the command is similar. Run this from the Web project directory:

```powershell
dotnet ef migrations add MIGRATIONNAME -c AppDbContext -p ../Your.ProjectName.Infrastructure/Your.ProjectName.Infrastructure.csproj -s Your.ProjectName.Web.csproj -o Data/Migrations
```

To use SqlServer, change `options.UseSqlite(connectionString));` to `options.UseSqlServer(connectionString));` in the `Your.ProjectName.Infrastructure.StartupSetup` file. Also remember to replace the `SqliteConnection` with `DefaultConnection` in the `Your.ProjectName.Web.Program` file, which points to your Database Server.

To update the database use this command from the Web project folder (replace `Clean.Architecture` with your project's name):

```powershell
dotnet ef database update -c AppDbContext -p ../Clean.Architecture.Infrastructure/Clean.Architecture.Infrastructure.csproj -s Clean.Architecture.Web.csproj
```

---

## File: docs/content/minimal-clean-architecture.md

---
title: "Minimal Clean Architecture"
weight: 30
---

# Minimal Clean Architecture

## Overview

The **Minimal Clean Architecture** template provides a simplified, pragmatic approach to Clean Architecture for ASP.NET Core applications. It maintains the core principles of Clean Architecture—separation of concerns, dependency inversion, and testability—while reducing complexity through a single-project Vertical Slice Architecture (VSA).

## Philosophy

### Core Principles

1. **Simplicity First**: Minimize unnecessary abstractions and project boundaries
2. **Vertical Slices**: Organize by feature rather than technical layer
3. **Pragmatic DDD**: Use domain patterns where they add value, not everywhere
4. **Progressive Enhancement**: Start simple, add complexity only when needed

### Clean Architecture Principles Maintained

- ✅ **Dependency Inversion**: Domain doesn't depend on infrastructure
- ✅ **Testability**: Business logic can be tested in isolation
- ✅ **Separation of Concerns**: Clear boundaries between domain, infrastructure, and presentation
- ✅ **Framework Independence**: Domain logic isn't coupled to ASP.NET Core

### Simplifications from Full Template

- **Single Project**: All code in one Web project instead of 4+ projects
- **Simplified DDD**: Essential patterns only (entities, aggregates) without extensive value objects, specifications
- **Optional CQRS**: Mediator is optional; logic can live in endpoints
- **Direct Data Access**: Can use DbContext directly or simple repositories instead of complex repository pattern
- **Vertical Organization**: Group by feature (Cart, Order, Product) instead of by layer

## Architecture

### Project Structure

```text
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/            # EF migrations
│   ├── Email/                     # External services
│   └── Services/                  # Infrastructure 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
```

### Vertical Slice Organization

Each feature (Cart, Order, Product) contains:

- **Domain**: Entities and business logic
- **Infrastructure**: Data configurations for that feature
- **Endpoints**: API endpoints for that feature

This keeps related code together, making it easier to understand and modify features independently.

### Dependency Flow

```text
Endpoints ──→ Domain
    ↓
Infrastructure ──→ Domain
```

- Endpoints can use Domain and Infrastructure
- Infrastructure depends on Domain (for entity configurations)
- Domain has no dependencies on other layers

## Design Decisions

### ADR-001: Single Project Architecture

**Status**: Accepted

**Context**: Need to balance architectural guidance with simplicity for smaller applications.

**Decision**: Use a single Web project with clear folder structure instead of multiple projects.

**Consequences**:
- ✅ Simpler to navigate and understand
- ✅ Faster builds (no project-to-project references)
- ✅ Easier to refactor (no project boundary concerns)
- ✅ Lower initial complexity
- ⚠️ Developers must respect folder boundaries (not enforced by compiler)
- ⚠️ Harder to enforce strict layer separation

**Migration Path**: Can be extracted into multiple projects later if needed.

### ADR-002: Vertical Slice Organization

**Status**: Accepted

**Context**: Need to organize code in a way that's easy to understand and modify.

**Decision**: Organize by feature (vertical slices) rather than by layer (horizontal).

**Consequences**:
- ✅ Related code is colocated (easier to find)
- ✅ Features can be modified independently
- ✅ Natural fit for microservices extraction
- ✅ Aligns with business capabilities
- ⚠️ May have some code duplication across features
- ⚠️ Shared concerns need careful consideration

### ADR-003: Pragmatic DDD

**Status**: Accepted

**Context**: Full DDD patterns can be overkill for simpler domains.

**Decision**: Use essential DDD patterns (entities, aggregates) but keep it simple.

**Patterns Included**:
- ✅ Entities with encapsulation
- ✅ Aggregate roots
- ✅ Domain events (optional)

**Patterns Simplified/Optional**:
- ⚠️ Value Objects (use when valuable, not everywhere)
- ⚠️ Specifications (use LINQ, add if needed)
- ⚠️ Domain Services (add only when needed)

**Consequences**:
- ✅ Easier to learn and apply
- ✅ Less boilerplate code
- ✅ Faster development
- ⚠️ May need to add patterns as domain complexity grows

### ADR-004: Optional Mediator/CQRS

**Status**: Accepted

**Context**: CQRS with Mediator adds valuable patterns but also complexity.

**Decision**: Make Mediator optional; allow business logic in endpoints for simple cases. Trade-off is no ability to use custom pipeline for cross-cutting concerns.

**Usage Guidelines**:
- Simple CRUD: Can put logic directly in endpoints
- Complex workflows: Use Mediator commands/queries
- Cross-cutting concerns: Use Mediator pipeline behaviors

**Consequences**:
- ✅ Lower initial complexity
- ✅ Developers choose appropriate level of abstraction
- ⚠️ Inconsistent patterns across codebase possible
- ⚠️ Need clear team guidelines on when to use Mediator

### ADR-005: FastEndpoints for APIs

**Status**: Accepted

**Context**: Need clean, testable API endpoints.

**Decision**: Use FastEndpoints with REPR pattern.

**Consequences**:
- ✅ One file per endpoint (easy to find)
- ✅ Built-in validation support
- ✅ Clear request/response types
- ✅ Testable without HTTP layer
- ⚠️ Different from standard ASP.NET Core patterns
- ⚠️ Learning curve for team

## When to Use This Template

### Ideal Scenarios

1. **MVPs and Prototypes**
   - Need to validate ideas quickly
   - Want architectural guidance without overhead
   - May grow into larger application

2. **Small to Medium Applications**
   - 5-50 endpoints
   - 5-20 domain entities
   - 1-5 developers
   - Simple to moderate domain complexity

3. **Learning Clean Architecture**
   - Want to understand principles without complexity
   - Stepping stone to full Clean Architecture
   - Teaching tool for teams

4. **Vertical Slice Architecture Preference**
   - Team prefers feature-based organization
   - Planning to extract microservices later
   - Value cohesion over layer separation

### Not Recommended For

1. **Large Enterprise Applications**
   - Complex domain requiring extensive DDD patterns
   - Multiple teams needing strict boundaries
   - Long-term evolution expected
   - → Use Full Clean Architecture instead

2. **Microservices from Start**
   - If you know you'll split into services
   - → Consider separate services with minimal template each

3. **Regulatory/Compliance Heavy**
   - Strict audit requirements
   - Need enforced layer boundaries
   - → Use Full Clean Architecture instead

## Migration Paths

### From Minimal to Full Clean Architecture

As your application grows, you can migrate to the full template:

#### Step 1: Extract Core Project

```powershell
# Create new Core project
dotnet new classlib -n YourProject.Core

# Move domain entities
mv Domain/* ../YourProject.Core/

# Update namespaces
# Update project references
```

#### Step 2: Extract Infrastructure Project

```powershell
# Create Infrastructure project
dotnet new classlib -n YourProject.Infrastructure

# Move infrastructure code
mv Infrastructure/* ../YourProject.Infrastructure/

# Add reference to Core
dotnet add YourProject.Infrastructure reference YourProject.Core
```

#### Step 3: Extract UseCases (Optional)

```powershell
# Create UseCases project
dotnet new classlib -n YourProject.UseCases

# Move business logic from endpoints to use cases
# Add Mediator (if not already using)
# Create command/query handlers
# Leverage Mediator Behaviors for cross-cutting concerns
```

#### Step 4: Clean Up Web Project

- Update project references
- Keep only endpoints and startup code
- Reference UseCases or Infrastructure as needed

### From Full Clean Architecture to Minimal

If you find the full template too complex:

#### Step 1: Merge Projects

```powershell
# Copy all code into Web project
# Organize by vertical slices
```

#### Step 2: Simplify Patterns

- Replace Specifications with LINQ
- Simplify Value Objects to primitives where beneficial
- Remove unnecessary abstractions

#### Step 3: Organize Vertically

- Group by feature instead of layer
- Colocate related code

## Best Practices

### Domain Layer

```csharp
// Good: Encapsulated entity
public class Cart
{
    private readonly List<CartItem> _items = new();
    public IReadOnlyCollection<CartItem> Items => _items.AsReadOnly();
    
    public void AddItem(Product product, int quantity)
    {
        // Business logic here
        var existingItem = _items.FirstOrDefault(i => i.ProductId == product.Id);
        if (existingItem != null)
        {
            existingItem.IncreaseQuantity(quantity);
        }
        else
        {
            _items.Add(new CartItem(product, quantity));
        }
    }
}

// Avoid: Anemic domain model
public class Cart
{
    public List<CartItem> Items { get; set; } = new();
}
```

### Endpoint Layer

```csharp
// Good: Clear, focused endpoint
public class CreateCart : EndpointWithoutRequest<CartResponse>
{
    private readonly AppDbContext _db;
    
    public CreateCart(AppDbContext db) => _db = db;
    
    public override void Configure()
    {
        Post("/carts");
        AllowAnonymous();
    }
    
    public override async Task HandleAsync(CancellationToken ct)
    {
        var cart = new Cart(guestUserId: Guid.NewGuid());
        _db.Carts.Add(cart);
        await _db.SaveChangesAsync(ct);
        
        await Send.Async(new CartResponse(cart.Id, cart.Items.Count), cancellation: ct);
    }
}
```

### Infrastructure Layer

```csharp
// Good: Focused EF configuration
public class CartConfiguration : IEntityTypeConfiguration<Cart>
{
    public void Configure(EntityTypeBuilder<Cart> builder)
    {
        builder.HasKey(c => c.Id);
        builder.HasMany(c => c.Items)
               .WithOne()
               .HasForeignKey("CartId");
    }
}
```

## Testing Strategy

### Unit Tests

Focus on domain logic:

```csharp
public class CartTests
{
    [Fact]
    public void AddItem_NewProduct_AddsToCart()
    {
        // Arrange
        var cart = new Cart(guestUserId: Guid.NewGuid());
        var product = new Product("Test", 10m);
        
        // Act
        cart.AddItem(product, 2);
        
        // Assert
        Assert.Single(cart.Items);
        Assert.Equal(2, cart.Items.First().Quantity);
    }
}
```

### Functional Tests

Test endpoints end-to-end:

```csharp
public class CartEndpointsTests : IClassFixture<WebApplicationFactory>
{
    [Fact]
    public async Task CreateCart_ReturnsNewCart()
    {
        // Arrange
        var client = _factory.CreateClient();
        
        // Act
        var response = await client.PostAsync("/carts", null);
        
        // Assert
        response.EnsureSuccessStatusCode();
        var cart = await response.Content.ReadFromJsonAsync<CartResponse>();
        Assert.NotNull(cart);
    }
}
```

## Resources

- [Main Clean Architecture Template](https://github.com/ardalis/CleanArchitecture)
- [Vertical Slice Architecture](https://jimmybogard.com/vertical-slice-architecture/)
- [FastEndpoints Documentation](https://fast-endpoints.com/)
- [Domain-Driven Design Fundamentals](https://www.pluralsight.com/courses/fundamentals-domain-driven-design)
- [Clean Architecture Course](https://academy.nimblepros.com/p/intro-to-clean-architecture)

## Contributing

Contributions are welcome! Please see the main [Contributing Guide](../CONTRIBUTING.md).

## License

MIT - see [LICENSE](../LICENSE)

## 2. Official Technical Reference & Guides (ardalis/docs)

## Microsoft Open Source Code of Conduct

This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.

ASP.NET Docs
============

This project provides the source for [docs.microsoft.com/aspnet](https://docs.microsoft.com/aspnet). You can learn more about ASP.NET Core at the [Home](https://github.com/aspnet/home) repo. See the [Contributing Guide](CONTRIBUTING.md) and the [issues list](\https://github.com/aspnet/Docs/issues) if you would like to help out.

API PR's ( *api/autoapi/...* ) should not be made here. Changes to API documentation should be made in the source repository against the triple slash /// comments. 

This project has adopted the [Microsoft Open Source Code of
Conduct](https://opensource.microsoft.com/codeofconduct/).
For more information see the [Code of Conduct
FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or
contact [opencode@microsoft.com](mailto:opencode@microsoft.com)
with any additional questions or comments.