📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you enforce architecture rules automatically in a .NET 10 solution? Show architecture tests with NetArchTest or ArchUnitNET, and explain how project references, internal visibility and analysers fit in.

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.

Senior Coding Advanced architecture architecture-tests archunitnet fitness-functions netarchtest roslyn-analysers

🎯 Key points

  • Layered defence: project references (compile-time direction), internal (visibility), architecture tests (rules the compiler can't express), analysers (code-level bans)
  • Architecture tests inspect compiled assemblies and run in xUnit/NUnit/MSTest in CI in seconds
  • NetArchTest.Rules: simple fluent API but last released 2021 — consider the maintained NetArchTest.eNhancedEdition fork; ArchUnitNET (TngTech): actively maintained, richer rules for layers and slices
  • Typical rules: Domain has no dependency on EF Core/ASP.NET Core; Application does not reference Infrastructure; modules only use other modules' Contracts; handlers are sealed
  • Banned API analyser (Microsoft.CodeAnalysis.BannedApiAnalyzers, RS0030) blocks APIs such as DateTime.Now or new HttpClient()
  • Roll out with a baseline: freeze existing violations, fail on new ones, burn down
  • Rules evolve with the architecture: version them with the code, change them through an ADR, delete rules that no longer earn their keep
  • Limits: static dependencies only — not runtime behaviour, reflection or raw SQL across schemas

⏱ 30-second answer

Make the rules executable at several levels:

  • Project references enforce dependency direction at compile time (Domain can't see Infrastructure if it doesn't reference it).
  • internal hides implementation types so other projects can't use them.
  • Architecture tests check rules the compiler can't: "Domain must not depend on 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.
  • Analysers, such as the banned-API analyser, block specific calls like 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I treat architecture rules like any other requirement: if they matter, they're tested. I layer the enforcement. First, project references: if Domain.csproj doesn't reference anything, the compiler guarantees it can't use EF Core. Second, internal: a module's handlers and DbContext are 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 from Program'. And fourth, Roslyn analysers for code-level bans, like the banned-API analyser rejecting DateTime.Now in favour of TimeProvider.

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."


Enforcement layers

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 vs ArchUnitNET (as of November 2026)

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

Rollout

  1. Write the rule and the reason (ADR).
  2. Run it against main; record existing violations as a baseline.
  3. Fail the build on any violation not in the baseline.
  4. Burn down the baseline, deleting entries as they are fixed.

Production example

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.

🔍 What the interviewer is checking

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

  • Layers enforcement: project references, internal, architecture tests, analysers
  • Writes concrete rules (Domain must not depend on EF Core; modules use only Contracts)
  • Knows NetArchTest's maintenance status and ArchUnitNET as an alternative
  • Describes a baseline-then-burn-down rollout and the limits of static checks

Red flags

  • Relies only on code review or a wiki page
  • Can't write a rule beyond a vague description
  • Believes architecture tests catch runtime or data-access violations

📚 Learn in depth

1. How architecture tests work

  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.

2. Which rules to write

Start with rules that protect the most expensive mistakes:

  1. Direction: Domain → nothing technical; Application → not Infrastructure; Presentation → not Infrastructure except the composition root.
  2. Module boundaries: module A only uses module B's Contracts namespace.
  3. No cycles between slices or modules (ArchUnitNET supports slice rules for this).
  4. Conventions that encode design: handlers are sealed; domain entities have no public setters; endpoints don't depend on DbContext.

Avoid style rules that analysers or .editorconfig already cover.

3. Analysers for code-level rules

  • Microsoft.CodeAnalysis.BannedApiAnalyzers reads BannedSymbols.txt and reports RS0030 for each use:
    • P:System.DateTime.Now;Use TimeProvider
    • M:System.Net.Http.HttpClient.#ctor;Use IHttpClientFactory
  • Custom Roslyn analysers for rules unique to your domain.
  • .editorconfig severity error (or TreatWarningsAsErrors) makes them blocking.

4. What the compiler can't see

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".

5. Limits

  • No view of runtime behaviour: DI resolution, reflection, dynamic loading.
  • No view of data access: a raw SQL string reading billing.Invoices from Orders. Use per-schema database users or query analysis (Query Store).
  • Rules can be brittle if tied to type names; prefer namespaces and assemblies.

6. Fitness functions

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.

Try it yourself

  1. Add an ArchUnitNET test that fails if Domain depends on Microsoft.EntityFrameworkCore, then add an EF Core attribute to an entity and watch it fail.
  2. Add Microsoft.CodeAnalysis.BannedApiAnalyzers and ban DateTime.Now; fix the violations with TimeProvider.
  3. Write a module-cycle rule and introduce a cycle deliberately.
  4. Implement a baseline file for existing violations and make the test fail only for new ones.
  5. Time the architecture test suite and confirm it adds seconds, not minutes, to CI.

💻 Code

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

⚠ Common mistakes

  • Mistake: Documenting architecture rules but relying on code review to enforce them. Why it is wrong: reviewers miss a dependency under deadline pressure, and drift accumulates silently. Instead: encode each important rule as a test or analyser that fails the build.
  • Mistake: Adding a dozen rules to a legacy solution in one go and breaking the build. Why it is wrong: the team disables the tests. Instead: baseline existing violations, fail only on new ones, and burn down.
  • Mistake: Choosing NetArchTest.Rules without checking its maintenance status. Why it is wrong: the original package hasn't been released since 2021. Instead: use ArchUnitNET or the maintained NetArchTest.eNhancedEdition fork, and pin versions.
  • Mistake: Loading the architecture model in every test. Why it is wrong: it makes the suite slow. Instead: build it once in a static field or fixture.
  • Mistake: Writing rules against type-name patterns only. Why it is wrong: renames break or bypass them. Instead: rule on namespaces and assemblies, and use names only for conventions.
  • Mistake: Believing architecture tests catch all boundary violations. Why it is wrong: they don't see raw SQL across schemas or runtime reflection. Instead: pair them with per-schema database permissions and integration tests.
  • Mistake: Rules with no recorded reason. Why it is wrong: people delete rules they don't understand. Instead: use .Because(...) and link the ADR.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate calls architecture tests fitness functions. Why: Checks whether they understand evolutionary architecture and other kinds of fitness functions.
    How to answer

    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.

  2. When: Candidate writes module boundary rules. Why: Checks whether they understand data ownership and contracts in a modular monolith.
    How to answer

    A modular monolith is one deployable split into modules aligned to business capabilities — Orders, Billing, Catalogue — each with hard boundaries.

    • Each module owns its data: its own schema and DbContext, no cross-module joins or foreign keys.
    • Modules talk only through a public contract (an interface and DTOs) or integration events; everything else is internal.
    • Boundaries are enforced: separate projects, 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.

  3. When: Candidate mentions writing a custom Roslyn analyser. Why: Checks whether they can build analysers and safe code fixes.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Boundary erosion discovered only during module extraction
Situation
A [6-module] .NET modular monolith for [insurance claims], [3] teams. The team planned to extract the Documents module and estimated [2 weeks].
Signals
The extraction spike surfaced [37] references from other modules into Documents' internal types via `InternalsVisibleTo` and public classes; [5] raw SQL queries read `documents.*` from other modules; the estimate grew to [5 weeks].
Investigation
Ran ArchUnitNET rules over all module assemblies to list cross-module dependencies; searched for `InternalsVisibleTo`; used Query Store to find statements touching more than one schema; reviewed git history to see when violations appeared.
Resolution
Immediately: baselined the 37 violations and failed the build on new ones. Then: replaced internal usages with calls through `Documents.Contracts`, moved the raw SQL behind contract methods, removed `InternalsVisibleTo` except for test projects, then extracted the module.
Prevention
Architecture tests for every module boundary in CI; a test banning `InternalsVisibleTo` to non-test assemblies; per-module database logins with schema-only grants; an ADR documenting the boundary rules.

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].

↩ Usually asked after

More in Application Architectures

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me