Zum Inhalt springen

A C# layer boundary as a tested architecture rule

A rule should report the domain's SQL access even through a bridge. Hit and miss cases show which version of the rule does that.

by CodeCharter
  • architecture
  • csharp
  • code-quality

The lead developer of an accounting module has to turn a decision from the architecture review into a CI gate. The domain logic in Ledger.Domain must not know the SQL store in Ledger.Sql. Shortly before, a refactoring moved the database access out of the invoice into a helper class:

namespace Ledger.Domain;
public sealed class Invoice
{
    private readonly Ledger.Adapters.Bridge bridge;
    public Invoice(Ledger.Adapters.Bridge bridge) => this.bridge = bridge;
    public string Post() => bridge.Write();
}
namespace Ledger.Adapters;
public sealed class Bridge(Ledger.Sql.Store store)
{
    public string Write() => store.Write();
}

Invoice.cs no longer names a SQL type, but the invoice still needs the store to post. The lead developer has to formulate the rule and decide whether it runs as a CodeCharter rule or as an architecture test with ArchUnitNET. The Ledger solution is constructed for this article. All outputs come from real runs with CodeCharter v1.7.0 and ArchUnitNET v0.13.5.

The obvious rule

The first version in rules/ledger-boundary.ccr selects the domain types and checks the types they use:

@name "Ledger boundary"
@severity error
@category "Architecture"

from t in AllTypesFlattened
where t.FullName.StartsWith("Ledger.Domain.")
where t.UsedTypes.Any(u => u.FullName.StartsWith("Ledger.Sql."))
select t

On the solution with the bridge, the gate stays green:

> codecharter analyze Ledger.sln --no-host --fail-on error
…
Rules: 1 from rules
No violations found.
  0 violations
  Analyzed 5 types, 5 methods in 7,2s

The process exits with status 0. A green run on the application only says that today's code satisfies the condition. It does not show whether the condition captures the architecture decision.

Hits and misses

The spec rules/ledger-boundary.spec.md sits next to the rule. Under ## hits are snippets the rule must report, under ## misses snippets it must not report. The lead developer writes both sides of the decision into it:

## hits

### Direct SQL type

```csharp
namespace Ledger.Domain { public class Invoice { public Ledger.Sql.Store Db { get; set; } } }
namespace Ledger.Sql { public class Store { } }
```

### SQL type created in a method body

```csharp
namespace Ledger.Domain { public class Invoice { public string Post() => new Ledger.Sql.Store().Write(); } }
namespace Ledger.Sql { public class Store { public string Write() => "sql"; } }
```

### Bridge outside the domain

```csharp
namespace Ledger.Domain { public class Invoice { public Ledger.Adapters.Bridge Port { get; set; } } }
namespace Ledger.Adapters { public class Bridge { public Ledger.Sql.Store Db { get; set; } } }
namespace Ledger.Sql { public class Store { } }
```

## misses

### Implementations depend on the contract

```csharp
namespace Ledger.Domain { public interface IStore { string Write(); } public class Invoice { public IStore Port { get; set; } public string Post() => Port.Write(); } }
namespace Ledger.Sql { public class Store : Ledger.Domain.IStore { public string Write() => "sql"; } }
```

The spec runner finds two gaps in the first version:

> codecharter test rules/ledger-boundary.ccr
FAIL ledger-boundary  (2/4 cases)
     ✗ Hit 'SQL type created in a method body' …
       …\ledger\rules\ledger-boundary.spec.md:10
     ✗ Hit 'Bridge outside the domain' …
       …\ledger\rules\ledger-boundary.spec.md:17

1/1 spec(s) failed (2/4 cases failing).

Both cases carry the message Expected the rule to flag this snippet (hit), but it produced no violation., which the console separates with a dash. The exit code is 1, so a pipeline stops here. The cause is in the description of UsedTypes in the DSL schema. The collection holds only solution types that a declaration names: base type, interfaces and signature types. A new Ledger.Sql.Store() in a method body is missing from it. At the bridge, the collection ends after the first step.

Transitive search in declared mode

The second version replaces only the condition:

where t.Reaches("Ledger.Sql.*", "declared")

Reaches is true when a directed path leads from the type to a solution type whose full name matches the pattern. The declared mode follows six edge kinds: inheritance, interface implementation, signature types, resolved calls, attributes and object creation. With it, the rule passes all four cases with exit code 0 and reports the invoice in the application:

> codecharter test rules/ledger-boundary.ccr
PASS ledger-boundary  (4/4 cases)

All 1 spec(s) passed (4/4 cases).
> codecharter analyze Ledger.sln --no-host --fail-on error
Rules: 1 from rules
  --- Error (1) ---

  ERROR  [Architecture] Ledger boundary
        Ledger.Domain.Invoice
        …\ledger\Ledger\Invoice.cs:2
…
  1 violation (1 error)
  Analyzed 5 types, 5 methods in 9,2s

With --fail-on error the run exits with status 1. The repair from the architecture review puts the contract IStore into the domain. Ledger.Sql.Store implements it, and Program.cs picks the implementation:

namespace Ledger.Domain;
public sealed class Invoice
{
    private readonly IStore store;
    public Invoice(IStore store) => this.store = store;
    public string Post() => store.Write();
}

After this refactoring, analyze reports no finding and exits with status 0. The implementation edge points from Ledger.Sql.Store to IStore, which is the permitted direction.

The miss case decides the mode. The dispatch mode additionally follows every implementation in the solution at each call through an interface. With "dispatch" in the same rule, the runner penalizes the refactoring:

> codecharter test rules/ledger-boundary.ccr
FAIL ledger-boundary  (3/4 cases)
     ✗ Miss 'Implementations depend on the contract' …
       …\ledger\rules\ledger-boundary.spec.md:27

1/1 spec(s) failed (1/4 cases failing).

The message reads Expected the rule to ignore this snippet (miss), but it produced 1 violation(s). analyze then also reports Ledger.Domain.Invoice on the repaired version. The miss case only has this effect because it calls Port.Write(). If a miss case names IStore only as a property type and does not call Write(), it passes with "dispatch" as well. Such a spec with three cases ran with exit code 0 in this case. codecharter validate accepts all three rule versions with exit code 0, because it checks only syntax and member references.

Architecture test with ArchUnitNET

ArchUnitNET reads the compiled assembly and runs in the normal dotnet test. The test project Ledger.ArchTests contains three versions of the same boundary:

[Fact]
public void Domain_does_not_depend_on_sql() =>
    Types().That().ResideInNamespaceOrBelow("Ledger.Domain")
        .Should().NotDependOnAny(Types().That().ResideInNamespaceOrBelow("Ledger.Sql"))
        .Check(Model);

[Fact]
public void Domain_depends_only_on_domain_and_system() =>
    Types().That().ResideInNamespaceOrBelow("Ledger.Domain")
        .Should().OnlyDependOnTypesThat().ResideInNamespaceMatching(@"^(Ledger\.Domain|System)(\..*)?$")
        .Check(Model);

[Fact]
public void Domain_reaches_no_sql_type()
{
    var offenders = Types().That().ResideInNamespaceOrBelow("Ledger.Domain").GetObjects(Model)
        .Where(type => Reachable(type).Any(t => t.FullName.StartsWith("Ledger.Sql.")))
        .Select(type => type.FullName);
    Assert.Empty(offenders);
}

Reachable is a ten-line breadth-first search over IType.Dependencies. The fluent API in v0.13.5 offers no transitive condition. On the state with the bridge, two of the three tests fail:

> dotnet test Ledger.ArchTests --nologo
…
   ArchUnitNET.xUnit.FailedArchRuleException : "Types that reside in namespace with full name "Ledger.Domain" or below should only depend on types that reside in namespace with full name matching "^(Ledger\.Domain|System)(\..*)?$"" failed:
	Ledger.Domain.Invoice does depend on Ledger.Adapters.Bridge
…
   Assert.Empty() Failure: Collection was not empty
Collection: ["Ledger.Domain.Invoice"]
…
Failed!  - Failed:     2, Passed:     1, Skipped:     0, Total:     3, Duration: 1 s - Ledger.ArchTests.dll (net9.0)
State ArchUnitNET direct deny list ArchUnitNET allow list ArchUnitNET breadth-first search CodeCharter UsedTypes CodeCharter declared
Bridge green red red green red
Contract IStore green green green green green
Contract plus Ledger.Domain.Audit with new Ledger.Sql.Store() in a method body red red red green red

The direct deny list misses the bridge, just like the first CodeCharter version. It does see the method body, because ArchUnitNET reads the IL. The allow list and the breadth-first search solve the case as well as Reaches. The patch series does not contain the state in the third row; it was created as an extra file in a working copy. NetArchTest.Rules v1.3.2 gave the same results as the direct deny list and the allow list of ArchUnitNET on all three states. At the bridge, HaveDependencyOn("Ledger.Sql") stayed green, and OnlyHaveDependenciesOn("Ledger.Domain", "System") reported the invoice.

ArchUnitNET has no harness for hit and miss cases. The green test on the repaired state says nothing about whether the first test would report a bridge. For that check, the team would need example types in a separate test assembly. This is a derivation; the case did not try it.

Choosing between rule and test

If the domain logic may know only itself and the base class library, the allow list in the ArchUnitNET test is enough. It needs no transitive search, no license and no extra tool in CI. The pattern System(\..*)? also admits System.Data, though. A domain type with a property of type System.Data.DataTable stayed green in all three tests in this case.

If the boundary lies at types outside the solution, such as System.Data or a NuGet package like EF Core, ArchUnitNET is the better choice. Reaches knows only solution types. Only System.Data was measured, EF Core was not. This counter-test comes from a working copy and is not part of the patch series. The rule t.Reaches("System.Data.*", "declared") did not report the type with the DataTable, and the CLI printed no hint about it. The ArchUnitNET test with NotDependOnAnyTypesThat().ResideInNamespaceOrBelow("System.Data") failed with Ledger.Domain.Report does depend on "System.Data.DataTable".

The CodeCharter rule fits when the domain logic may use helper types outside the domain and only one namespace of the own solution is off limits. An allow list would then have to enumerate every permitted namespace, while Reaches expresses the deny list in one line. The spec records both sides of the decision, and analyze reports the finding with file and line. When the rule moves to another solution, the dot in "Ledger.Domain." keeps Ledger.DomainTools out of the selection. A misspelled prefix selects no type and leaves the gate green. That is why the rollout includes a known hit in the target solution, like the bridge state here. None of the versions reports a dependency that only arises through reflection or a name in the DI container. According to its interface description, Reaches is blind to this, and the IL analysis sees only types the code names. Spec format and exit codes and predicates describe the details.

Patch series and commands

The patch series contains the .NET 9 solution, rule, spec, test project and three editing states. It requires a .NET 9 SDK, access to nuget.org and a CodeCharter CLI with a valid license.

curl -fsSLo ledger.patch.txt https://codecharter.tools/article-examples/ledger.patch.txt
git init ledger
cd ledger
git -c user.name=Reader -c user.email=reader@example.invalid am ../ledger.patch.txt
git switch --detach ':/01 Direct rule'
codecharter test rules/ledger-boundary.ccr
codecharter analyze Ledger.sln --no-host --fail-on error
dotnet test Ledger.ArchTests
git switch --detach ':/02 Transitive rule'
codecharter test rules/ledger-boundary.ccr
codecharter analyze Ledger.sln --no-host --fail-on error
git switch --detach ':/03 Contract'
codecharter analyze Ledger.sln --no-host --fail-on error
dotnet test Ledger.ArchTests

The exit codes in order: 1, 0, 1, 0, 1, 0, 0. The test project is not part of Ledger.sln, so analyze checks only the application.