What is a module boundary in a modular monolith dotnet codebase?
A module in a modular monolith is a vertical slice of the business, such as Orders, Billing or Catalog, that owns its data and behaviour. Its boundary is the line between what other modules are allowed to touch and what they are not. In a modular monolith dotnet solution, that line is drawn by splitting each module into two parts.
- Public surface: contracts (request and response DTOs), integration events, and a single facade or API interface such as
IOrdersModule. These types change slowly and are versioned deliberately. - Internals: domain entities, value objects, the
DbContextand its migrations, repositories, command and query handlers, and validators. These change often and should be free to change.
The rule is that a module may depend only on another module's public surface. It may never depend on that module's internals. Billing can call IOrdersModule.GetOrderSummary or handle an OrderPlaced event. It cannot query the Orders tables or construct an Order entity. This rule lets each module refactor its domain and schema without coordinating with every other module. It also keeps a later extraction into a separate service a mechanical change rather than a rewrite.
The target dependency shape
- Orders, Billing and Catalog each depend on the Shared Kernel. The Shared Kernel holds only primitives such as
Money, base event types and result types. It depends on no module. - Billing depends on
Orders.ContractsandCatalog.Contracts. - Orders depends on
Catalog.Contracts. - No contracts assembly depends on any module's internals.
- There are no cycles.
The architecture tests in later sections encode exactly this shape.
+----------------------+ +----------------------+ +----------------------+
| Billing internals | | Orders internals | | Catalog internals |
| domain, DbContext, | | domain, DbContext, | | domain, DbContext, |
| repos, handlers | | repos, handlers | | repos, handlers |
+----------+-----------+ +-------------------+--+ +----------------------+
| +----------------------+
+---------------------+--------------------------+ |
v v v
+----------------------+ +----------------------+ +----------------------+
| Billing.Contracts | | Orders.Contracts | | Catalog.Contracts |
| IBillingModule, DTOs | | IOrdersModule, DTOs | | ICatalogModule, DTOs |
| integration events | | OrderPlaced event | | integration events |
+----------+-----------+ +----------+-----------+ +----------+-----------+
| | |
+--------------------------+--------------------------+
v
+------------------------------------+
| Shared Kernel |
| Money, base event types, results |
| depends on no module |
+------------------------------------+
Arrows = allowed compile-time dependency. No arrow may end in internals.
Each module's internals also use its own contracts and the Shared Kernel.
Target dependency shape: modules reach each other only through Contracts, all depend on a Shared Kernel that depends on nothing, and there are no cycles.
Why aren't 'internal' and separate projects enough to protect module boundaries?
The compiler enforces visibility and the absence of reference cycles. It does not enforce intent, and module boundaries erode in the space between those two.
Where the compiler stops helping
InternalsVisibleTopunches holes. It usually starts with a test project, then a "temporary" grant to a sibling module that needs one helper. After that,internalno longer means "private to this module." It means "private to this module and whoever asked."- Catch-all
CommonorSharedprojects absorb domain logic. Every module may reference them, so moving a type there makes it reachable everywhere. A pricing rule placed inSharedbecomes a hidden dependency between Orders and Catalog that no project reference reveals. - Project references are cheap to add. A developer who needs a type from
Catalog.Corecan add a reference in seconds. The build stays green, the review diff shows one line in a.csproj, and Orders now depends on Catalog's internals. - A single large assembly per module hides internal structure. Everything inside one project can see everything else. Your domain layer can call infrastructure, and handlers can reach into another feature's persistence code, with no compiler error.
Why rules must run on every build
A boundary that is only documented gets checked only during reviews, and only when a reviewer happens to notice. If the rules run as tests in CI, each violation fails the build at the moment someone introduces it. At that point the fix is a single change rather than a migration.
This matters most when you have several modules, many contributors who don't all carry the architecture in their heads, and rules that project references can't express, such as "only Contracts namespaces may be referenced across modules" or "the domain layer must not use EF Core types."
How do you set up an ArchUnitNET architecture test project?
Create a dedicated test project, for example App.ArchitectureTests, next to your other test projects. Give it project references to every module assembly you want to check. Add the core TngTech.ArchUnitNET package and the integration package for your test framework, such as the xUnit or NUnit variant. The integration package turns a violated rule into a normal test failure that lists the offending types, so CI reports it like any other broken test.
ArchUnitNET reads compiled assemblies, and loading them is the slow part of the test run. Load them once into a single Architecture object. Use ArchLoader, pass it your own assemblies only, and hold the result in a static field that every test class shares. Leave out framework and third-party assemblies. Loading them makes the run slower and puts types into the model that you never write rules about.
Before writing rules, settle on a namespace convention, because every rule will match against it. A workable shape is App.Modules.<Module>, with three sub-namespaces:
.Contractsfor the public surface other modules may use.Domainfor entities and business logic.Infrastructurefor persistence and integrations
Write this convention down in the repository so that new code follows it.
Then define each module once as a named type selection, such as "all types residing in App.Modules.Orders and its sub-namespaces." Do the same for each module's Contracts slice. Rules can then refer to Orders and OrdersContracts by name. When a namespace is renamed, you change one definition, and the rules themselves don't need editing.
#!/usr/bin/env bash
set -euo pipefail
# Create a dedicated architecture test project next to the other test projects.
dotnet new xunit -n App.ArchitectureTests -o tests/App.ArchitectureTests
# Add it to the solution so CI builds and runs it with everything else.
dotnet sln App.sln add tests/App.ArchitectureTests/App.ArchitectureTests.csproj
# Reference every module assembly whose boundaries should be checked.
# Only the application's own projects go here. ArchLoader will load these
# assemblies, not framework or third-party ones.
dotnet add tests/App.ArchitectureTests/App.ArchitectureTests.csproj reference \
src/Modules/Orders/App.Modules.Orders.csproj \
src/Modules/Billing/App.Modules.Billing.csproj \
src/Modules/Shipping/App.Modules.Shipping.csproj
# Core library: ArchLoader, the Architecture model, and the fluent rule API.
dotnet add tests/App.ArchitectureTests/App.ArchitectureTests.csproj package TngTech.ArchUnitNET
# xUnit integration: a violated rule fails the test and lists the offending types.
# NUnit teams would add TngTech.ArchUnitNET.NUnit instead.
dotnet add tests/App.ArchitectureTests/App.ArchitectureTests.csproj package TngTech.ArchUnitNET.xUnit
# Run the architecture tests the same way as any other test project.
dotnet test tests/App.ArchitectureTests/App.ArchitectureTests.csproj
Shell commands that create the App.ArchitectureTests project, reference only the application's module assemblies, and add the core ArchUnitNET package and its xUnit integration package.
How do you write architecture tests that isolate modules from each other?
The core rule reads: types in Orders must not depend on any type in Billing, except types in BillingContracts. Don't write it by hand for each pair. Keep a single list of module names in the test project and generate one test case per ordered pair, for example with an xUnit theory fed by that list. With five modules that is twenty cases. Adding a sixth module means adding one entry to the list, and its rules exist before anyone writes code in it. A failure names the exact pair, such as "Orders → Billing", so the developer sees which edge broke without reading a long violation dump.
Layering inside a module
Within each module, the Domain namespace must not depend on that module's Infrastructure namespace or on Microsoft.EntityFrameworkCore. The EF Core rule matters because a single DbContext or [Owned] attribute leaking into an entity is how persistence concerns spread into the domain without anyone noticing. Also require that Contracts does not depend on the module's own internals. If a contract exposes an internal type, every consumer now relies on it indirectly, and the cross-module rule cannot catch that.
Shared code
Shared must not depend on any module. Otherwise it becomes a back channel between modules. Restrict which kinds of types Shared may contain, such as value objects, abstractions, and primitives, so it does not slowly fill with business logic.
Completeness
Finally, assert that every type in the loaded assemblies belongs to a known module, its contracts, or Shared. Without this check, a namespace typo like Order.Domain places types outside every rule, and all the other tests keep passing.
// C# (xUnit + ArchUnitNET): cross-module rules generated from one list, plus a completeness check
using System.Collections.Generic;
using System.Linq;
using ArchUnitNET.Domain;
using ArchUnitNET.Loader;
using ArchUnitNET.xUnit;
using Xunit;
using static ArchUnitNET.Fluent.ArchRuleDefinition;
public class ModuleBoundaryTests
{
// Single source of truth. A new module gets its rules as soon as it is listed here.
static readonly string[] Modules = { "Orders", "Billing", "Catalog", "Shipping", "Customers" };
// Marker types (placeholders) pull each module assembly into the analysis.
static readonly Architecture Arch = new ArchLoader()
.LoadAssemblies(typeof(Shop.Orders.OrdersModule).Assembly, typeof(Shop.Billing.BillingModule).Assembly,
typeof(Shop.Catalog.CatalogModule).Assembly, typeof(Shop.Shipping.ShippingModule).Assembly,
typeof(Shop.Customers.CustomersModule).Assembly, typeof(Shop.Shared.SharedMarker).Assembly)
.Build();
// Matches a namespace and everything beneath it, e.g. Shop.Billing and Shop.Billing.Domain.
static string Ns(string name) => $@"^Shop\.{name}(\..*)?$";
// Every ordered pair: 5 modules -> 20 cases, each reported separately, e.g. (Orders, Billing).
public static IEnumerable<object[]> ModulePairs =>
from a in Modules from b in Modules where a != b select new object[] { a, b };
[Theory, MemberData(nameof(ModulePairs))]
public void Module_does_not_reach_into_other_module_internals(string from, string to) =>
Types().That().ResideInNamespace(Ns(from), true)
.Should().NotDependOnAny(Types().That().ResideInNamespace(Ns(to), true)
.And().DoNotResideInNamespace(Ns(to + @"\.Contracts"), true))
.Because($"{from} -> {to} may only use {to}.Contracts")
.Check(Arch);
[Fact]
public void Every_type_belongs_to_a_known_module_or_shared() =>
// A typo such as Shop.Order.Domain lands outside the allowed set and fails here.
Types().That().ResideInNamespace(@"^Shop(\..*)?$", true)
.Should().ResideInNamespace(Ns("(" + string.Join("|", Modules.Append("Shared")) + ")"), true)
.Check(Arch);
}
A C# xUnit test class (ArchUnitNET) that generates one boundary rule per ordered module pair from a single module list, allows only each target module's Contracts namespace, and fails if any type lives outside the known module or Shared namespaces.
How do you adopt architecture rules on an existing codebase and act on failures?
Rules on an existing codebase only help if each failure tells the reader what to fix. Attach a reason to every rule with Because(...) that names the module and the boundary it protects. Then assert on the rule's evaluation result so the failure output lists each violating type and the type it depends on. "Rule failed" is not actionable. "Billing.Domain.InvoiceService depends on Orders.Infrastructure.OrderRepository" is.
Record current violations instead of disabling the rule
On a legacy codebase the first run will fail, often heavily. Do not comment the rule out. Turn its current violations into an explicit exclusion list of fully qualified type names. Keep the list in one file next to the tests, and give each entry an owning team and a short reason. The rule then fails only on new violations. Removing an entry is a reviewable change that shows progress, so the list should get shorter over time and never longer.
Run in CI with the unit tests
Put the architecture tests in the same test run that gates pull requests. A new cross-module reference then fails the PR before it merges. To keep the tests fast and deterministic:
- Load the architecture once and share it across tests, for example in a static field or a shared test fixture.
- Load only your own module assemblies, not framework or third-party assemblies.
Illustrative estimate: cost of catching a violation late
All inputs below are assumptions:
| Assumption | Value |
|---|---|
| Fix at PR time, while the author has context | 0.5 hours |
| Same fix during a later extraction (trace callers, redesign the contract, retest) | 6 hours |
| New violations per quarter | 10 |
At PR time, 10 violations cost about 5 hours. During a later extraction, the same 10 cost about 60 hours. That is roughly 55 engineer-hours saved per quarter.
{
"purpose": "Known boundary violations recorded when the rules were introduced. The rule ignores only these types. Entries may be removed, never added.",
"rules": {
"ModulesDoNotReferenceOtherModulesInfrastructure": [
{
"type": "Billing.Domain.InvoiceService",
"dependsOn": "Orders.Infrastructure.OrderRepository",
"owner": "team-billing",
"reason": "Reads order totals directly; replace with an Orders public contract query",
"tracking": "BILL-142"
},
{
"type": "Shipping.Application.DispatchHandler",
"dependsOn": "Inventory.Infrastructure.StockDbContext",
"owner": "team-fulfilment",
"reason": "Legacy stock check; move behind an Inventory integration event",
"tracking": "FUL-87"
}
],
"DomainDoesNotDependOnInfrastructure": [
{
"type": "Orders.Domain.OrderPricing",
"dependsOn": "Orders.Infrastructure.PriceCache",
"owner": "team-orders",
"reason": "Cache lookup inside the domain; inject a pricing port instead",
"tracking": "ORD-311"
}
]
}
}
An owned exclusion list, kept next to the architecture tests, that records each existing violation by fully qualified type name together with its dependency, owning team and reason, so the rules fail only on new violations and the list can shrink through reviewable deletions.
What are the alternatives to ArchUnitNET for enforcing module boundaries?
ArchUnitNET is one of several ways to keep modules apart. The others differ in how hard they stop a violation, how quickly a developer finds out, and how much they cost to run over time.
| Approach | Enforcement strength | Feedback speed | Granularity | Setup cost | Ongoing maintenance |
|---|---|---|---|---|---|
Separate assemblies with internal types |
Strong. The compiler rejects the reference | Instant, in the IDE | Coarse: project and type visibility | Medium to high | Low, but InternalsVisibleTo can erode it |
| ArchUnitNET architecture tests | Medium. Fails the build only if tests run in CI | Test run or CI | Fine: namespaces, naming, attributes, dependency direction | Low | Medium. Rules must track renames and new modules |
| Folder conventions plus code review | Weak. Depends on reviewer attention | PR review, often late | Whatever reviewers remember | Very low | High and hidden |
| Fully separate services | Very strong. No shared process | Deploy or integration time | Coarse: network contract | Very high | High: deployment, versioning, observability |
Separate assemblies give the strongest in-process isolation. A forbidden dependency fails to compile, so the developer sees it while typing. Architecture tests are the better fit when splitting a module into several projects would hurt build times or require a large refactor. They also fit rules that project references cannot express, such as "only *.Contracts namespaces may be referenced across modules" or "domain types must not depend on EF Core."
The two work best together. Use assemblies to set the hard outer walls. Use ArchUnitNET for the rules inside and between those walls. Add tests that fail when someone introduces InternalsVisibleTo or a new project reference, because those are the usual ways the compiler's protection gets bypassed.
When should you avoid relying on architecture tests, and what do they miss?
Even with those guards, the tests only see what the compiled assemblies reference. ArchUnitNET analyses static type dependencies, so any coupling that never shows up as a type reference passes.
| Coupling | Caught by ArchUnitNET? | What catches it instead |
|---|---|---|
| Direct reference to another module's types | Yes | — |
| Shared tables or queries against another module's schema | No | Per-module schemas and database permissions |
| Reflection or type names in strings | No | Code review, runtime tests |
| Message types matched by string name | No | Contract tests on message shapes |
| Another module's service resolved from the DI container at runtime | No | Integration tests that build each module's container in isolation |
The rules are also structural, not judgements about design. A module can pass every rule while exposing a chatty public contract that leaks its internal model, so callers still change in lockstep with it.
Strictness has costs. Rules that ban all sharing push teams to duplicate code or invent contracts that exist only to satisfy the test. Modules drawn more finely than the real domain seams add coordination work without adding isolation. Exclusion lists tend to become permanent. Give each exception an owner and a review date, or the list quietly becomes the real architecture. On large solutions, loading every assembly also slows the suite, so the rules may need to run in a separate CI stage.
The cost is worth paying when several teams share one codebase and you expect to extract modules later. It is not worth paying for a small team with one deployable and unsettled domain boundaries. There, the rules mostly lock in guesses.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to modular monolith dotnet, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- The dependency graph answers "what does this touch?" in seconds instead of a manual audit.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- You can size a change's blast radius before merging, avoiding surprise cross-team firefighting.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.