What is a modular monolith in .NET, and why aren't folders and namespaces enough?
A modular monolith is a single deployable application, in .NET usually one ASP.NET Core process, divided into modules that each own one business capability, such as Ordering, Billing or Catalog. It ships as one unit, but the boundaries between modules are enforced by the compiler, not by team discipline.
Folders and namespaces don't provide that enforcement. They are conventions. If Billing lives in /Billing under the Shop.Billing namespace, a class in Shop.Ordering can still add a using directive and call any public type in Billing, including its repositories and its EF Core entities. The build succeeds. The only check is a reviewer who notices the dependency. Over months, many of those small shortcuts accumulate into tight coupling.
Separate projects change this in two ways:
- Project references are explicit and acyclic. Ordering can only use Billing if its project file references Billing, and MSBuild rejects circular references. Each dependency is visible in the project file and has to be added on purpose.
- The
internalmodifier is scoped to the assembly. If you mark Billing's implementation typesinternaland expose only a small public contract, then any code outside Billing that touches those types fails to compile.
A forbidden dependency becomes a build error instead of a review comment. That is the main reason to use this structure: it reduces coupling and the review time spent catching it.
The approach suits teams that ship one deployable but have a growing codebase and several distinct business areas. Draw the module boundaries around business capabilities, not technical layers. Splitting into Web, Services and Data projects still leaves every feature spread across all three projects, so nothing is actually isolated.
How should you lay out module projects and project boundaries?
Two projects per module
Give each module exactly two projects to start with:
Ordering.Contractsis public. It contains DTOs, integration events and the service interfaces other modules may call, such asIOrderLookup. Keep it small and free of dependencies, because every type in it is a promise to other teams.Orderingis the implementation. It holds the domain model, theDbContext, handlers and endpoint mappings. Almost every type here isinternal. For example,internal sealed class OrderLookup : IOrderLookupsits next to aninternal class Orderaggregate. Only the interface it implements is visible outside the assembly.
Reference rules
These rules work because the compiler enforces assembly boundaries. Namespace boundaries are not enforced:
OrderingreferencesOrdering.Contractsand the shared building blocks project (for example, base types for results and events).- Other modules reference only
Ordering.Contracts, through a<ProjectReference Include="..\Ordering.Contracts\Ordering.Contracts.csproj" />entry. - Only the host references
Ordering.csprojitself. - Building blocks reference no module.
When Billing cannot reference Ordering, it cannot reach into Order or the DbContext, even by accident. The internal modifier stops reflection-free access across assemblies. Avoid InternalsVisibleTo except for the module's own test project.
Don't split further by default
Split a module into more projects (separate domain or infrastructure assemblies) only for a concrete reason, such as a dependency you need to isolate. Each extra project lengthens solution load and build times and adds another csproj file to maintain.
<!-- Billing/Billing.csproj: other modules reference only the contract -->
<ItemGroup>
<ProjectReference Include="..\Ordering.Contracts\Ordering.Contracts.csproj" />
</ItemGroup>
<!-- Ordering/Ordering.csproj: implementation sees its contracts and building blocks -->
<ItemGroup>
<ProjectReference Include="..\Ordering.Contracts\Ordering.Contracts.csproj" />
<ProjectReference Include="..\BuildingBlocks\BuildingBlocks.csproj" />
<!-- Only the module's own tests may see internals -->
<InternalsVisibleTo Include="Ordering.Tests" />
</ItemGroup>
// Ordering.Contracts/IOrderLookup.cs: public, every type here is a promise
namespace Ordering.Contracts;
public sealed record OrderSummary(Guid OrderId, decimal Total, string Status);
public interface IOrderLookup
{
Task<OrderSummary?> FindAsync(Guid orderId, CancellationToken ct);
}
// Ordering/OrderLookup.cs: internal, invisible to Billing at compile time
internal sealed class OrderLookup(OrderingDbContext db) : IOrderLookup
{
public Task<OrderSummary?> FindAsync(Guid orderId, CancellationToken ct) =>
db.Orders.Where(o => o.Id == orderId)
.Select(o => new OrderSummary(o.Id, o.Total, o.Status.ToString()))
.FirstOrDefaultAsync(ct);
}
// Ordering/OrderingModule.cs: the one public entry point, called only by the host
public static class OrderingModule
{
public static IServiceCollection AddOrderingModule(this IServiceCollection services)
{
services.AddScoped<IOrderLookup, OrderLookup>();
return services;
}
}
The csproj ProjectReference entries for a consuming module and for the implementation project. The C# code shows the public IOrderLookup contract implemented by an internal class, which the module exposes only through a public registration method that the host calls.
How does a single ASP.NET Core host compose the modules?
Each module exposes exactly two public members: an IServiceCollection extension method such as AddOrdersModule that registers its services, and an IEndpointRouteBuilder extension such as MapOrdersEndpoints that maps its routes. Program.cs calls the Add… method for each module, builds the app, then calls each Map… method. It references nothing else inside the modules. A reader can see the whole composition in a dozen lines, and adding a module means adding two calls.
These entry points work with internal types because they are compiled into the module's own assembly. Inside the extension method, the module can register an internal implementation against an internal or public interface. The DI container resolves services through reflection at runtime and does not check C# accessibility, so it constructs internal classes without complaint. Handlers, repositories and the module's DbContext can all stay internal.
Do not make a type public just because a framework seems to require it. Check the actual constraint first. MVC's default controller discovery, for example, only picks up public classes. You can map minimal API endpoints from inside the module instead, or adjust discovery. Each type you make public "for the framework" becomes something other modules can call, and the boundary weakens.
The cost of a single host is operational. There is one deployment unit, one process and one shared failure domain. A memory leak or thread-pool starvation in one module degrades every other module. You also cannot scale a busy module on its own. Scaling out means scaling the whole application.
// Orders/OrdersModule.cs (C#, Orders module assembly)
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
namespace Orders;
// The only public surface of the module: one method for services, one for endpoints.
public static class OrdersModule
{
public static IServiceCollection AddOrdersModule(this IServiceCollection services)
{
// Internal interface and implementation: the container builds them without them being public.
services.AddScoped<IOrderRepository, InMemoryOrderRepository>();
return services;
}
public static IEndpointRouteBuilder MapOrdersEndpoints(this IEndpointRouteBuilder endpoints)
{
// Minimal APIs mapped here, so no public controller is needed for discovery.
var group = endpoints.MapGroup("/orders");
group.MapGet("/{id:guid}", async (Guid id, IOrderRepository repo) =>
await repo.FindAsync(id) is { } order ? Results.Ok(order) : Results.NotFound());
return endpoints;
}
}
internal sealed record OrderDto(Guid Id, decimal Total);
internal interface IOrderRepository { Task<OrderDto?> FindAsync(Guid id); }
internal sealed class InMemoryOrderRepository : IOrderRepository
{
public Task<OrderDto?> FindAsync(Guid id) => Task.FromResult<OrderDto?>(null);
}
// Host/Program.cs: composes modules through their entry points and nothing else.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOrdersModule().AddBillingModule();
var app = builder.Build();
app.MapOrdersEndpoints();
app.MapBillingEndpoints();
app.Run();
An Orders module (C#) that exposes only AddOrdersModule and MapOrdersEndpoints while keeping its repository and DTO internal, and a Program.cs that composes modules using just those calls.
How should modules communicate and own their data?
A module talks to another module only through its Contracts project, never through its domain entities or repositories. If Billing loads an Order entity or calls OrderRepository, it now depends on Orders' internal model and persistence. Every refactor in Orders can break Billing, and the boundary exists only on paper.
There are two ways to cross a boundary. A synchronous call through an interface in Contracts, such as IOrderLookup.GetSummaryAsync, fits queries where the caller needs an answer now. An in-process event such as OrderPlaced fits notifications where the publisher should not know or care who reacts. Watch the call graph closely. If a single request goes from module to module to module through interfaces, you have built a distributed-monolith call graph inside one process. That usually means the boundaries are drawn around technical layers instead of business capabilities.
Each module owns its data. Give it one DbContext, ideally mapped to its own schema, with entities marked internal. Modules do not query or join each other's tables. Of every rule in this guide, data ownership decides most directly whether you could extract a module later.
Separate data stores make consistency an explicit choice:
| Option | Consistency | Coupling | Fits when |
|---|---|---|---|
| Sync interface call | Immediate read | Runtime dependency | Caller needs data now |
| In-process event | Eventual | Low | Side effects, notifications |
| Event plus outbox | Eventual, durable | Low | Losing an event is unacceptable |
| Shared transaction | Atomic | High, recouples modules | Rare invariants that cannot be split |
A shared transaction across two DbContexts is atomic, but it ties the modules back together at the database. Treat it as a sign to reconsider the boundary rather than as a default.
// Orders.Infrastructure (C#, EF Core). Nothing here is visible to other modules.
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
// Internal entity: other modules cannot reference it, only Contracts DTOs.
internal sealed class Order
{
public Guid Id { get; set; }
public string CustomerId { get; set; } = "";
public decimal Total { get; set; }
}
// One DbContext per module, internal to the module.
internal sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options)
: DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Every table this module maps lands in the "orders" schema.
modelBuilder.HasDefaultSchema("orders");
modelBuilder.Entity<Order>().HasKey(o => o.Id);
}
}
// The module's only public surface for wiring persistence into the host.
public static class OrdersModuleRegistration
{
public static IServiceCollection AddOrdersPersistence(
this IServiceCollection services, string connectionString)
{
services.AddDbContext<OrdersDbContext>(o => o.UseSqlServer(
connectionString,
// Keep migration history per module so schemas evolve independently.
sql => sql.MigrationsHistoryTable("__EFMigrationsHistory", "orders")));
return services;
}
}
An Orders module DbContext pinned to its own "orders" schema and migrations history table, with an internal entity and context so that only the registration method is public.
How do you keep internal visibility and boundaries from eroding over time?
The compiler only protects a boundary as long as nobody opens it. InternalsVisibleTo is the most common way it gets opened, so restrict it to test projects. In SDK-style projects this is a single item in the module's csproj, <InternalsVisibleTo Include="Orders.Tests" />, which is easy to review. If you find an entry naming another module, the boundary is already gone.
Reflection works around internal without leaving anything in the csproj. Some serializers, object mappers, ORMs and test frameworks can read or construct non-public types. Your code then still compiles cleanly while another module depends on your internals. Record each such case as a known leak, with the reason and an owner, so it stays a deliberate decision.
Visibility rules alone are not enough, so add three more checks:
- Architecture tests. Run them in CI and have them assert dependency rules, such as "no module references another module's implementation assembly" or "only the host references every module."
Directory.Build.props. Put shared settings likeNullable,TreatWarningsAsErrorsand the target framework in one file at the repository root. This stops individual modules from drifting into looser configurations.- One composition root. Only the host registers services and wires modules together. A module that resolves another module's services has created a hidden dependency.
Put cross-cutting concerns such as auth, logging, transaction handling and configuration binding into small building-block projects, each with a narrow purpose. Be careful with a project called "Shared" or "Common." Each addition looks harmless, but over time it collects domain types, helpers and DTOs from every module. Once every module depends on that project, they are coupled to each other through it, and the compiler no longer blocks that coupling.
<!-- Directory.Build.props (repository root): applied to every project below it -->
<Project>
<PropertyGroup>
<!-- One target framework so no module drifts onto a different runtime -->
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<!-- Warnings fail the build, so modules cannot quietly loosen settings -->
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
</Project>
<!-- src/Modules/Orders/Orders.csproj -->
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<!-- The only exception to 'internal': the module's own test project.
An entry naming another module here means the boundary is gone. -->
<InternalsVisibleTo Include="Orders.Tests" />
</ItemGroup>
<ItemGroup>
<!-- Allowed: the module's own public contracts and a narrow building block -->
<ProjectReference Include="..\Orders.Contracts\Orders.Contracts.csproj" />
<ProjectReference Include="..\..\BuildingBlocks\Logging\BuildingBlocks.Logging.csproj" />
<!-- Not allowed: references to other modules' implementation projects.
Architecture tests in CI should fail the build if one appears. -->
</ItemGroup>
</Project>
A root Directory.Build.props that enforces shared build settings across all modules, and a module csproj that exposes internals only to its own test project and references only contracts and a narrow building-block project.
How should you test a modular monolith?
Testing follows the same boundaries as the code. Each test level answers a different question, so no single level has to cover everything.
Unit tests inside a module
Each module gets its own test project, and the module grants it access with a single InternalsVisibleTo entry naming that project only. The tests can then exercise internal handlers, domain rules and validators directly, while other modules still see only the public contract. Keep the grant to one test assembly per module. If one shared test project can see every module's internals, it becomes a path for coupling between modules.
Module-level integration tests
These tests call only the module's public contracts, such as its commands, queries and published events, against real infrastructure like the module's own database schema. Because they can't reach internals, they keep passing when you refactor inside the module and fail when the contract's behavior changes.
Host-level tests
WebApplicationFactory<TEntryPoint> from Microsoft.AspNetCore.Mvc.Testing boots the real host in memory. Use it to check that the host is assembled correctly: every module registers its services, the DI container resolves them, routes map to the right endpoints, and middleware runs in order. Keep these tests few and focused on wiring rather than business logic.
Why this saves time
When the compiler enforces boundaries, reviewers spend less time on layering comments, because a disallowed reference doesn't build. A change inside a module runs that module's tests first, so feedback stays local. A failing test also points to a specific module, which makes it clear which team owns the fix.
When should you avoid a modular monolith, and what are the alternatives?
A modular monolith is one point on a spectrum. The useful comparison is with its nearest neighbours:
| Approach | Boundary strength | Development cost | Build time | Deployment and scaling | Operational overhead |
|---|---|---|---|---|---|
| Layered monolith | Weak; layers, not domains | Lowest upfront | Fast, one project | One unit, scaled as a whole | Low |
| Single project, namespaces plus architecture tests | Medium; enforced by tests, not the compiler | Low | Fast | One unit | Low |
| Modular monolith | Strong; compiler and internal |
Moderate upfront | Slower, many projects | One unit | Low |
| Microservices | Strongest; network and data | Highest | Fast per service | Independent per service | High |
When to avoid it
Skip the structure for small or short-lived applications. The project scaffolding costs more than the coupling it prevents. Also hold off when the domain boundaries are still unclear. A wrong seam that the compiler enforces is expensive to fix: every feature crosses it, and each crossing forces contract changes in two modules. A single project with namespace rules lets you move code freely until the boundaries settle. If a workload needs independent scaling or fault isolation, a module cannot provide either. All modules share one process, one memory space and one deployment.
The cost trade
You pay upfront in project files, contracts and build time. In return, coupling costs stay lower later. That trade only pays off if the codebase lives long enough and grows large enough.
Not a migration plan
A module is not a service waiting to be extracted. Extraction still requires several pieces of work:
- Contracts that handle latency and partial failure.
- A separate database and a data migration.
- Deployment and monitoring for the new service.
Future-proofing alone does not justify the structure.
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.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
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.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- 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.