Shows how to make architecture rules executable in .NET: project references, internal visibility, architecture tests with NetArchTest or ArchUnitNET, Roslyn analysers and banned APIs, and how to roll them out in CI.
Make the rules executable at several levels:
internal hides implementation types so other projects can't use them.Microsoft.EntityFrameworkCore", "Billing may only use Orders.Contracts". ArchUnitNET (actively maintained) or NetArchTest (the original is unmaintained since 2021; the eNhancedEdition fork is maintained) inspect compiled assemblies inside a normal test run.DateTime.Now.Roll out with a baseline so legacy violations don't block the build. The trade-off: cheap, fast feedback, but only for static dependencies.
"I treat architecture rules like any other requirement: if they matter, they're tested. I layer the enforcement. First, project references: if
Domain.csprojdoesn't reference anything, the compiler guarantees it can't use EF Core. Second,internal: a module's handlers andDbContextare internal, so another module physically can't call them. Third, architecture tests for the rules the compiler can't express — 'Application must not depend on Infrastructure namespaces', 'handlers must be sealed', 'the API project only touches Infrastructure fromProgram'. And fourth, Roslyn analysers for code-level bans, like the banned-API analyser rejectingDateTime.Nowin favour ofTimeProvider.For the tests themselves, as of late 2026 I'd pick ArchUnitNET from TNG for anything non-trivial: it's actively maintained, has integrations for xUnit, NUnit and MSTest, and can express layers, slices and cycles. NetArchTest.Rules has a lovely fluent API but hasn't had a release since 2021; there's a maintained fork, NetArchTest.eNhancedEdition, if a team likes that style. Either way, they load compiled assemblies and check type dependencies, so they run in seconds in the normal test stage of CI. For example, on [a modular monolith with N modules], we added [about 20] rules; [the first run found 37 violations], so we baselined them, failed only on new ones, and [burned the list down to zero over two sprints].
The mistake I see is writing a rules document and relying on code review. Reviewers miss a dependency under deadline pressure; a test never does. But I'm also clear about the limits: these tools see static type dependencies, not a raw SQL query reading another module's schema, so I pair them with per-schema database permissions."
| Layer | Catches | Doesn't catch | Feedback |
|---|---|---|---|
| Project references | Wrong dependency direction between projects | Rules inside a project; namespace-level rules | Compile error |
internal visibility |
Use of another project's implementation types | Misuse inside the same assembly | Compile error |
| Architecture tests | Namespace/type rules, naming, sealing, layer and module rules, cycles | Runtime behaviour, raw SQL, reflection | Test failure in CI |
| Analysers (banned APIs, custom) | Specific API calls, patterns | Cross-assembly structure | IDE squiggle + build error |
| Database permissions | Cross-schema data access | Code structure | Runtime error |
| NetArchTest.Rules | ArchUnitNET (TngTech) | |
|---|---|---|
| Maintenance | Last release 1.3.2 (2021); maintained fork NetArchTest.eNhancedEdition | Actively released (0.13.x line) |
| API style | Types.InAssembly(...).ShouldNot().HaveDependencyOn(...) |
Rules over a loaded Architecture: Types().That()...Should()...Check(arch) |
| Strengths | Very simple, quick to adopt | Layers, slices, cycles, richer predicates, test framework integrations |
| Weaknesses | Fewer rule types | Steeper learning curve |
In a 6-module monolith, 18 architecture tests ran in 1.4 seconds on every PR. In the first quarter they blocked 23 boundary violations before merge; before the tests, the team had found boundary breaks only during a module extraction, where they cost about 3 weeks of rework.
Checks that the candidate can turn architecture rules into automated checks, knows the current tooling and its limits, and can roll it out pragmatically.
Green flags
internal, architecture tests, analysersRed flags
dotnet test
|
v
Load compiled assemblies (Mono.Cecil)
|
v
Build a model: types, namespaces, dependencies (fields, params, base types, calls, attributes)
|
v
Evaluate rules: "types in X should not depend on Y"
|
v
Pass / fail with the list of offending types
They inspect IL-level dependencies, so they catch a dependency through a method parameter, a field, a base class, an attribute or a method call — not just using directives.
Start with rules that protect the most expensive mistakes:
Contracts namespace.sealed; domain entities have no public setters; endpoints don't depend on DbContext.Avoid style rules that analysers or .editorconfig already cover.
BannedSymbols.txt and reports RS0030 for each use:
P:System.DateTime.Now;Use TimeProviderM:System.Net.Http.HttpClient.#ctor;Use IHttpClientFactory.editorconfig severity error (or TreatWarningsAsErrors) makes them blocking.Api --> Application --> Domain
| ^
+--> Infrastructure (only Program.cs should use it)
Api references Infrastructure so Program.cs can call AddInfrastructure(), which means an endpoint could also use an Infrastructure type and compile fine. An architecture test closes that gap: "types in Api other than the composition root should not depend on Infrastructure".
billing.Invoices from Orders. Use per-schema database users or query analysis (Query Store).Neal Ford, Rebecca Parsons and Patrick Kua call these architectural fitness functions: automated checks that an architecture characteristic still holds. Architecture tests are the structural kind; latency budgets in load tests and vulnerability gates in the pipeline are others.
Domain depends on Microsoft.EntityFrameworkCore, then add an EF Core attribute to an entity and watch it fail.Microsoft.CodeAnalysis.BannedApiAnalyzers and ban DateTime.Now; fix the violations with TimeProvider.Architecture tests with ArchUnitNET (xUnit), plus a banned-API analyser configuration.
// tests/Architecture.Tests/LayerRules.cs
namespace Architecture.Tests;
using ArchUnitNET.Domain;
using ArchUnitNET.Fluent;
using ArchUnitNET.Loader;
using ArchUnitNET.xUnit;
using Xunit;
using static ArchUnitNET.Fluent.ArchRuleDefinition;
public sealed class LayerRules
{
// Load once: building the model is the slow part.
private static readonly Architecture Architecture = new ArchLoader()
.LoadAssemblies(
typeof(Shop.Domain.Orders.Order).Assembly,
typeof(Shop.Application.Orders.AddOrderLineHandler).Assembly,
typeof(Shop.Infrastructure.Persistence.InfrastructureRegistration).Assembly)
.Build();
private static readonly IObjectProvider<IType> Domain =
Types().That().ResideInNamespace("Shop.Domain").As("Domain");
private static readonly IObjectProvider<IType> Application =
Types().That().ResideInNamespace("Shop.Application").As("Application");
private static readonly IObjectProvider<IType> Infrastructure =
Types().That().ResideInNamespace("Shop.Infrastructure").As("Infrastructure");
[Fact]
public void Domain_has_no_framework_dependencies() =>
Types().That().Are(Domain)
.Should().NotDependOnAny(Types().That().ResideInNamespace("Microsoft.EntityFrameworkCore"))
.Because("the domain must stay persistence-ignorant (ADR-004)")
.Check(Architecture);
[Fact]
public void Application_does_not_depend_on_Infrastructure() =>
Types().That().Are(Application)
.Should().NotDependOnAny(Infrastructure)
.Because("Infrastructure implements Application's ports, not the other way round")
.Check(Architecture);
[Fact]
public void Handlers_are_sealed() =>
Classes().That().HaveNameEndingWith("Handler")
.Should().BeSealed()
.Check(Architecture);
}
ArchUnitNET is still on a 0.x version line, and namespace-matching overloads have changed between releases (some take a useRegularExpressions flag); check the signatures for the version you pin.
<!-- Directory.Build.props: banned APIs for every project -->
<Project>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.BannedApiAnalyzers" Version="4.*" PrivateAssets="all" />
<AdditionalFiles Include="$(MSBuildThisFileDirectory)BannedSymbols.txt" />
</ItemGroup>
</Project>
# BannedSymbols.txt (RS0030 reports any use)
P:System.DateTime.Now;Use TimeProvider so time is testable
P:System.DateTime.UtcNow;Use TimeProvider so time is testable
M:System.Net.Http.HttpClient.#ctor;Use IHttpClientFactory or a typed client
.Because(...) and link the ADR.Architecture tests are the cheapest fitness functions you'll ever write: a few lines, a second or two of CI time, and they stop the slow erosion that kills modular designs. The senior skill is choosing few, high-value rules — dependency direction, module boundaries, cycles — and introducing them without stopping delivery (baseline, then burn down). I also pick the enforcement level deliberately: compile-time where possible, tests for structural rules, analysers for API bans, database permissions for data boundaries.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
Project references + internal only |
Small solutions with clear project boundaries | Free | Rules inside a project or at namespace level |
| Architecture tests (ArchUnitNET / NetArchTest fork) | Any layered or modular solution | Minutes to write, seconds to run | Throwaway prototypes |
| Custom Roslyn analyser | Domain-specific code rules needing IDE feedback | Days to write and maintain | When a banned-API list or architecture test suffices |
| DB permissions per module | Modular monoliths with schema ownership | Connection-string and grant management | Single-schema apps |
Track violations caught per month and the size of the baseline over time; a growing baseline means the rules aren't being respected.
Evolutionary architecture (Ford, Parsons and Kua) is architecture designed to support guided, incremental change, rather than a fixed upfront design. The key tool is fitness functions: automated checks that protect the characteristics you care about, such as dependency rules (architecture tests), latency budgets, or startup time, run in CI or production. Around that, I keep boundaries modular (often a modular monolith first), make decisions reversible where possible and defer irreversible ones to the last responsible moment, record decisions in ADRs, and rely on continuous delivery, feature flags and observability so each change is small and safe.
A modular monolith is one deployable split into modules aligned to business capabilities — Orders, Billing, Catalogue — each with hard boundaries.
DbContext, no cross-module joins or foreign keys.internal.internal types, architecture tests, even per-schema database permissions.You get microservice-style boundaries with monolith-style operations: one pipeline, in-process calls, easy refactoring. The trade-off: one runtime, one release and one scaling unit, and it only works if the boundaries are enforced — otherwise it decays into a big ball of mud.
A code fix is a class deriving from CodeFixProvider, exported with [ExportCodeFixProvider(LanguageNames.CSharp)] and [Shared]. It lists the diagnostic ids it can fix in FixableDiagnosticIds, and in RegisterCodeFixesAsync finds the syntax at the diagnostic's location and registers a CodeAction that returns a new Document (or Solution). Give each action an equivalenceKey and return WellKnownFixAllProviders.BatchFixer from GetFixAllProvider so users can apply it to a document, project or solution. A safe fix preserves trivia (comments and formatting), adds simplifier and formatter annotations, never changes behaviour silently, and is covered by tests that compare before and after source.
How to tell it (STAR)
**S:** On [our claims platform], a [2-week] module extraction ballooned to [5 weeks] because of [37] hidden boundary violations. **T:** I wanted to finish the extraction and make sure it never happened again. **A:** I introduced ArchUnitNET boundary rules, baselined existing violations so the build stayed green, and wrote an ADR adding per-module database logins. Each team then burned down its own violations as part of normal work. **R:** The baseline reached [zero] in [two sprints], the tests blocked [23] new violations in the next quarter, and the following extraction took [8 days].
Last updated 23 Nov 2026.