Part 1 of 12 in Clean Architecture in .NET
Setting Up a Clean Architecture Solution in .NET
· 13 min read
A Clean Architecture solution stays clean when the build enforces its rules, not when everyone remembers them. This article sets up a .NET solution where project references, architecture tests, analyzers and CI do that work.
This is the first part of a series where I build an ecommerce API the way I’d start a real project: the solution setup first, then the foundation of each layer, then the features. The complete code is in my EcommerceApp repository, so you can see where each piece ends up. Each part explains the important code and uses only what earlier parts built. It ends with a link to the full code at that point, so you can build along or compare your work. This part is the solution itself: which projects exist, how they reference each other, and which rules every project follows.
None of the building blocks in this series are new. Rich entities and domain events come from Domain-Driven Design (Eric Evans), commands and queries from CQRS (Greg Young), and decorators from the Gang of Four book. I first learned how to put them together in .NET from Milan Jovanović’s articles and his Pragmatic Clean Architecture course. This series shows how I set them up in one project, the choices I made, and why.
The four projects and the dependency rule
The dependency rule points inward: the outer layers depend on the core, and never the other way around.
In EcommerceApp each layer is its own project, and the project references follow the rule:
Ecommerce.Domainreferences nothing.Ecommerce.ApplicationreferencesEcommerce.Domain.Ecommerce.InfrastructurereferencesEcommerce.ApplicationandEcommerce.Domain.Ecommerce.APIreferencesEcommerce.ApplicationandEcommerce.Infrastructure.
Create them from an empty folder:
dotnet new sln -n EcommerceApp --format slnx
dotnet new classlib -n Ecommerce.Domain
dotnet new classlib -n Ecommerce.Application
dotnet new classlib -n Ecommerce.Infrastructure
dotnet new webapi -n Ecommerce.API --use-controllers
dotnet add Ecommerce.Application reference Ecommerce.Domain
dotnet add Ecommerce.Infrastructure reference Ecommerce.Application Ecommerce.Domain
dotnet add Ecommerce.API reference Ecommerce.Application Ecommerce.Infrastructure
dotnet sln add Ecommerce.Domain Ecommerce.Application Ecommerce.Infrastructure Ecommerce.API
Delete the generated Class1.cs files, and the weather forecast controller, class and .http file from the API project.
Why separate projects instead of folders in one project? Because then the compiler enforces the dependency rule. If the Domain project has no reference to EF Core or to Infrastructure, no one can use them there by mistake: the build fails. With folders, the rule only exists as long as everyone remembers it.
What goes in each layer
A quick map of the terms the rest of the series uses:
- Domain: the business rules. Entities such as
ProductandOrder, value objects such asMoney, the errors a rule can return, domain events, and domain services for rules that span more than one entity. - Application: the use cases. Each request is a command (it changes something) or a query (it reads something), and a handler runs it: it loads what it needs, calls the domain and saves. Application also declares interfaces for what it needs from outside, such as the database (
IApplicationDbContext), the clock or email. - Infrastructure: the implementations of those interfaces. The EF Core
DbContextthat talks to PostgreSQL, the email sender, the cache. - API: the entry point. Controllers turn HTTP requests into commands and queries, and the results back into responses.
Program.csconnects the layers.
Application, Infrastructure and the API each have their own DependencyInjection.cs with one extension method, and register their own services. Domain has none, because it registers nothing. Program.cs only calls one method per layer:
builder.Services
.AddApplication()
.AddPresentation()
.AddInfrastructure(builder.Configuration);
Architecture tests close the gap
That call is why the API project references Infrastructure. But the reference also means a controller could use an Infrastructure class directly, and the compiler would allow it. Project references can’t stop that.
Architecture tests can. Add a small test project, Ecommerce.ArchitectureTests, that uses ArchUnitNET to load the four assemblies and check the dependencies between them:
using System.Reflection;
using ArchUnitNET.Fluent.Extensions;
using ArchUnitNET.Loader;
using ArchUnitNET.xUnitV3;
using Architecture = ArchUnitNET.Domain.Architecture;
using static ArchUnitNET.Fluent.ArchRuleDefinition;
// Loaded by name, so the tests also work while a new solution's Domain project has no types yet.
private static readonly Assembly Domain = Assembly.Load("Ecommerce.Domain");
private static readonly Assembly Application = typeof(Application.DependencyInjection).Assembly;
private static readonly Assembly Infrastructure = typeof(Infrastructure.DependencyInjection).Assembly;
private static readonly Assembly Api = typeof(Program).Assembly;
private static readonly Architecture Architecture = new ArchLoader()
.LoadAssemblies(Domain, Application, Infrastructure, Api)
.Build();
The other three layers each have their DependencyInjection class from the start, so typeof can find them. In a new solution, each method only returns services, for example public static IServiceCollection AddApplication(this IServiceCollection services) => services;. AddInfrastructure has the same body and also takes an IConfiguration. Application and Infrastructure need the Microsoft.Extensions.DependencyInjection.Abstractions package for IServiceCollection, and Infrastructure needs Microsoft.Extensions.Configuration.Abstractions for IConfiguration. Domain has no types yet, so it’s loaded by name. The cost is that a typo or a renamed project fails when the tests run, not when they compile. Loading by name works because the test project references the API, so Ecommerce.Domain.dll is copied to its output.
Each rule is then a test. Types() comes from the using static of ArchRuleDefinition above. The Architecture alias imports only that one type from ArchUnitNET.Domain. Why not the whole namespace? Because it has its own Assembly type, which would clash with System.Reflection.Assembly:
[Fact]
public void Controllers_Should_NotDependOnInfrastructure()
{
Types().That().HaveFullNameStartingWith("Ecommerce.API.Controllers.")
.Should().NotDependOnAny(Types().That().ResideInAssembly(Infrastructure))
.WithoutRequiringPositiveResults()
.Check(Architecture);
}
By default, ArchUnitNET fails a rule that matches no types. There are no controllers yet, so WithoutRequiringPositiveResults() lets the rule pass until the first one exists.
To check that the test really catches something, I added a class under Controllers that used Ecommerce.Infrastructure.DependencyInjection. The test failed with:
Ecommerce.API.Controllers.Probe.ProbeViolation does depend on "Ecommerce.Infrastructure.DependencyInjection"
The other three tests check rules the project references already enforce:
- Domain depends on no other layer.
- Application doesn’t depend on Infrastructure or the API.
- Infrastructure doesn’t depend on the API.
They are cheap, and they catch it if someone adds the wrong project reference later. The tests run in CI on every pull request (covered below).
Directory.Build.props: one place for build settings
MSBuild looks for the nearest Directory.Build.props above each project and imports it. So settings that every project should share go there once, instead of being copied into every .csproj file:
<Project>
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<AnalysisLevel>latest</AnalysisLevel>
<AnalysisMode>All</AnalysisMode>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1900</WarningsNotAsErrors>
</PropertyGroup>
</Project>
The last line is about vulnerable packages, covered below. After this, a project file only says what is different about that project: its packages and its references. Ecommerce.Domain.csproj is just this:
<Project Sdk="Microsoft.NET.Sdk">
</Project>
Analyzers, with warnings as errors
AnalysisMode set to All turns on almost every .NET analyzer rule, and the solution adds SonarAnalyzer.CSharp on top. TreatWarningsAsErrors makes every one of them fail the build.
Why does that matter? Because some of these rules catch real security mistakes. Here is what happens when a password is hashed the weak way:
- Lowering the PBKDF2 iterations to 1,000 fails with S5344: “Use at least 100,000 iterations here.”
- Hashing a password with MD5 fails with CA5351.
- Using the old
Rfc2898DeriveBytesconstructor, which defaults to SHA-1, fails with CA5379.
None of these is about style. Each one is a security mistake, and the code still compiles and works.
The nullable rules are the same kind of check. With Nullable enabled, a possible null value is a compiler warning. With CS8600 and CS8603 turned off, these mistakes get through. For example, Uri.TryCreate(..., out Uri uri) needs out Uri? uri, because the out value is null when parsing fails. As errors, they have to be fixed before the code can be merged, instead of showing up as a NullReferenceException in production.
I keep warnings as errors for two reasons:
- Consistency in a team. A warning can be ignored. An error can’t. So everyone working on the project follows the same rules, because code that breaks them doesn’t build.
- Fewer bugs. Mistakes like the ones above have to be fixed before merging, instead of being found in production.
What it costs
All turns on many more rules than Recommended, the mode below it, and some of them don’t fit the project.
I still use All. Why? Because new rules are on by default, and I decide what to turn off instead of deciding what to turn on. So the cost is a list of suppressions to maintain, and each SDK upgrade can add rules that flag code that was fine before.
Two habits keep the list honest. The suppressions live in .editorconfig at the solution root (more on that file below). Every suppression has its reason next to it, and the reason is about this codebase:
# CA2007: Consider calling ConfigureAwait on the awaited task. ASP.NET Core has no synchronization context, so ConfigureAwait adds nothing.
dotnet_diagnostic.CA2007.severity = none
That reason holds for the whole solution because the Application and Infrastructure libraries are only used by the ASP.NET Core API. And a rule that doesn’t fit some projects is turned off only in those projects:
[Ecommerce.ArchitectureTests/**.cs]
# CA1707: Identifiers should not contain underscores. Test names use Method_Should_Result.
dotnet_diagnostic.CA1707.severity = none
These are examples, and the solution won’t build with only them. Start from the full .editorconfig for this part, which gives the reason for every rule it turns off.
Without these habits, the list only grows. A rule gets turned off to silence one warning and stays off, even after it no longer hides anything. Or it hides a problem that should have been fixed in the code.
.editorconfig and code style
Directory.Build.props turns the rules on. .editorconfig defines them, including code style with an explicit severity:
dotnet_style_qualification_for_field = false:error
dotnet_style_require_accessibility_modifiers = for_non_interface_members:error
Without EnforceCodeStyleInBuild, these style rules only show up in the IDE. With it, dotnet build checks them too, so CI fails on the same rules a developer sees in the editor. The build respects the :error suffix from .NET 9 onward. On older SDKs, set the severity with dotnet_diagnostic.IDExxxx.severity instead.
CI: restore, build and test on every pull request
The analyzers and the architecture tests only help if every change goes through them, not only the ones built on a careful developer’s machine. So a GitHub Actions workflow restores, builds and tests the solution on every pull request to main:
name: CI
on:
pull_request:
branches: [main]
permissions: {}
jobs:
build-and-test:
runs-on: ubuntu-latest
permissions:
contents: read
env:
# Standard property for CI builds: deterministic paths in the build output.
ContinuousIntegrationBuild: true
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0
with:
dotnet-version: 10.0.x
- name: Restore
run: dotnet restore EcommerceApp.slnx
- name: Build
run: dotnet build EcommerceApp.slnx --no-restore --configuration Release
- name: Test
run: |
dotnet test --project Ecommerce.ArchitectureTests --no-build --configuration Release
dotnet test --project is the Microsoft.Testing.Platform form, which xunit v3 runs on. A global.json at the solution root selects it:
{
"test": {
"runner": "Microsoft.Testing.Platform"
}
}
Pull requests can come from anyone, so the workflow gets as few permissions as possible:
permissions: {}takes every permission away from the workflow’s token. The job gets back onlycontents: read, to check out the code.persist-credentials: falsekeeps that token out of the checked-out repo, so a later step can’t reuse it.- Each action is pinned to a commit SHA, with the version as a comment. A tag like
v7can be moved to other code. A SHA can’t.
--no-restore and --no-build stop each step from redoing the one before it.
A failing pipeline only blocks a merge if the check is required. On GitHub, that is a branch protection rule. Set main to require a pull request and a passing build-and-test check, and apply the rule to admins too. Then no change reaches main without the pipeline passing.
Central package management
Without it, every project file carries its own package versions, and they drift apart. One analyzer can end up in seven places: Directory.Build.props adds it at one version, and each of six projects overrides it with another. Set it up before the first package, while there is nothing to move.
Central package management (CPM) puts all versions in one file, Directory.Packages.props, at the solution root. In this part it holds the settings, the analyzer, the two abstractions packages and the packages the architecture test project needs. Delete the Microsoft.AspNetCore.OpenApi reference the API template added, and the AddOpenApi and MapOpenApi lines in Program.cs, because nothing uses them yet:
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
<!-- A PackageVersion also pins the package when it only comes in transitively, e.g. to move off a vulnerable version. -->
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
</PropertyGroup>
<ItemGroup>
<GlobalPackageReference Include="SonarAnalyzer.CSharp" Version="10.30.0.144632" Condition="$(MSBuildProjectExtension) == '.csproj'" />
</ItemGroup>
<ItemGroup Label="Application">
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.13" />
</ItemGroup>
<ItemGroup Label="Infrastructure">
<PackageVersion Include="Microsoft.Extensions.Configuration.Abstractions" Version="10.0.13" />
</ItemGroup>
<ItemGroup Label="Tests">
<PackageVersion Include="TngTech.ArchUnitNET.xUnitV3" Version="0.13.4" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageVersion Include="xunit.v3" Version="4.0.2" />
</ItemGroup>
</Project>
The test project lists the packages it uses, without versions, and references the API project, which brings the other three layers with it. This is Ecommerce.ArchitectureTests/Ecommerce.ArchitectureTests.csproj. Add it to the solution with dotnet sln add Ecommerce.ArchitectureTests:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="TngTech.ArchUnitNET.xUnitV3" />
<PackageReference Include="xunit.v3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Ecommerce.API\Ecommerce.API.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>
Adding a package always works the same way: a PackageVersion line here, under a Label for its layer, and a PackageReference without a version in the project that uses it.
A project still decides which packages it uses, and Directory.Packages.props decides the version. A Version left on a PackageReference fails restore with NU1008, so versions can’t creep back. If one project really needs a different version, it can use VersionOverride.
GlobalPackageReference adds SonarAnalyzer to every project without a PackageReference in any of them. The condition keeps it out of projects that aren’t C#, such as a Visual Studio Docker Compose project.
Upgrading a package is then a change to one line in one file.
Vulnerable packages fail every build
NuGet checks packages for known vulnerabilities during restore and reports them as NU1901 to NU1904 (low to critical). For projects targeting .NET 10, the check covers transitive packages too. With TreatWarningsAsErrors, these are errors, so a vulnerable package fails the build on a developer’s machine, in CI and in the Docker image build. It can’t be merged or deployed.
At this point the solution only has SonarAnalyzer and the test packages, so there is little to flag. It starts to matter when the solution gets its first runtime packages.
The one exception is NU1900, the last line in Directory.Build.props. It means the vulnerability data couldn’t be downloaded, for example when offline. The check didn’t run, so nothing is known to be vulnerable, and it stays a warning.
What does this cost? The check fails builds, never a running application: the version in production keeps running. So the cost is timing. An advisory can be published at any time, and from then on every build fails. If the next build is an urgent fix for production, that fix is blocked until the package is dealt with.
The error names the package and the advisory, so the fix is one line in Directory.Packages.props:
- Upgrade the package’s
PackageVersionto a fixed version. For a transitive package, add aPackageVersionfor it, and transitive pinning moves every project to that version. Then run the tests, because an upgrade can change behavior. - If there is no fixed version yet, or an urgent fix can’t wait for the upgrade to be tested, suppress only that advisory with
<NuGetAuditSuppress Include="<advisory URL>" />, write the reason next to it, and remove it with the upgrade.
Microsoft’s NuGet documentation recommends another setup: keep NU1901 to NU1904 as warnings in normal builds and fail only a dedicated audit pipeline, so a new advisory doesn’t block an unrelated bug fix. For now I fail every build instead, to keep things simple.
Turning the audit off would bring back the problem: nothing would stop a vulnerable package from being merged.
The full code at the end of this part is at series-part-1.