DEV Community

Cover image for Simplifying modular monolith composition in .NET
Wojciech Wentland
Wojciech Wentland

Posted on Originally published at blog.wentland.io

Simplifying modular monolith composition in .NET

A layered .NET application splits code by technical role: endpoints in one project, handlers in another, the domain model and data access in their own. Adding a field to an order touches all four. Vertical slices split the same code by feature. Everything orders needs, from the endpoint to the query, sits together, and the change stays in one place.

Layers and vertical slices. The same code drawn twice. Rows are layers (endpoints, handlers, domain, data), columns are features (orders, billing, reporting). Cut into layers, a change to orders touches four projects; cut into slices, it stays inside one.

A modular monolith groups slices into modules and puts boundaries between them that a build can check. Orders may call billing through billing's public contract, but not read its tables or use its internal classes, and an architecture test fails if it tries. It still ships from one codebase, as one application or a handful of processes.

Modules and the host. Four modules in a row: orders, billing, reporting, identity. Neighbouring modules talk only through public contracts, which architecture tests check. Above them, the host project references every module and nothing checks it.

Those tests cover the modules and exempt the host. The host references every module, because something has to register them, and it decides which ones each process runs. In every setup I've built, that decision was a side effect of something else: which projects a host referenced, what a mediator found in an assembly, what a shared AddX() helper pulled in, which if branches matched a flag. None of them gave me a list I could read, or one a test could build.

Every process should be able to list what it runs and who registered each piece.

Fifteen hosts

The first version was in an earlier project. I wanted each vertical slice to run as its own process so it could scale on its own, which meant a host project per slice. There were fifteen of them in the end, each with a Program.cs that composed what its slice needed.

To avoid fifteen copies of the same registrations, I moved them into extension methods on IServiceCollection, and each host called the ones it needed:

// Orders.Host/Program.cs
builder.Services.AddOrders();

// Reporting.Host/Program.cs
builder.Services.AddReporting();
builder.Services.AddOrders(); // reports read orders

public static IServiceCollection AddOrders(this IServiceCollection services)
{
    services.AddScoped<OrderReader>();
    services.AddScoped<OrderService>();
    services.AddHostedService<OrderExpiryWorker>();   // now also runs in Reporting
    services.AddMessaging();                          // and so do its consumers
    services.AddOptions<PaymentOptions>().BindConfiguration("Payments")
        .ValidateDataAnnotations().ValidateOnStart();
    return services;
}
Enter fullscreen mode Exit fullscreen mode

The helpers grew to fit the host that needed the most. The reporting host wanted OrderReader and got the expiry worker, the message consumers and a payments section it had to configure. Nothing failed in the build. Each process started more than it used, and reading a host's Program.cs didn't tell me what it would end up running.

Deployment was worse. Each host had its own Dockerfile, and each one copied the project files it needed before dotnet restore. A new project meant a new COPY line in every Dockerfile whose host referenced it, directly or through another project. When I missed one, restore failed in CI. The images were built in one job, so one missing line failed all of them, and the fix meant rebuilding every image instead of one. I missed it more than once, and so did coding agents: they added the project, the reference and the registration, and the build passed locally, where nothing copies project files one by one.

Some problems got past CI. An image built, and the host failed when it started in the deployed environment, because a helper it called now needed a section or a service that host had never been given.

The mediator that wanted every handler

The same project used Mediator.Net for in-process requests. Its recommended setup scans an assembly and registers every handler it finds. The handlers of several slices lived in assemblies each host referenced anyway, so every host got all of them, each registered as a container service. The mediator only creates a handler when a message arrives, but in the Development environment ASP.NET Core validates every registered service when the host is built (ValidateOnBuild). On my machine, a host that served one slice didn't start until it registered the dependencies of handlers it would never call.

Mediator.Net can also take an explicit list of handlers. I tried it. It works, and it gives you a hand-written list per host, which is the fifteen-hosts problem in a different file. At that point the mediator wasn't giving me anything I needed, so I removed it.

Choosing which assemblies to scan doesn't help either. The unit I deploy is a process, and a process runs parts of several assemblies.

One executable with role flags

My current project went the other way: one executable, one image, and a flag that says which roles a process runs.

// dotnet App.dll serve --roles api,worker
var roles = RoleSet.Parse(args);

builder.Services.AddOrders();
if (roles.Contains(Role.Api)) builder.Services.AddPublicApi();
if (roles.Contains(Role.Worker))
{
    builder.Services.AddHostedService<OrderExpiryWorker>();
    if (!roles.Contains(Role.Api)) builder.Services.AddApiClient(); // call the API process instead
}
Enter fullscreen mode Exit fullscreen mode

That fixed the images. The one Dockerfile still lists every project file before restore, but a new project is one edit instead of one per Dockerfile that needed it, CI builds one image, and the number of processes stopped being a build problem.

The problem moved into composition. The branches spread from Program.cs into the helpers, and the helpers started taking the role set as a parameter. Eleven roles as free flags allow 2,047 combinations. Tests covered a handful of them. Which combinations I supported wasn't written down anywhere, and the reason a service was registered in a process was whichever branch had added it.

if (role) around extension methods is a reasonable design at a few branches, and I'd still use it there. It stops working when nobody can say, without reading every branch, who registered a service and which processes need it.

Declaring what a process runs

What I wanted was the list from the top of this post, built from declarations that sit next to the code they register:

  • A component declares the services it registers, the components it requires, the configuration sections it reads, and what it adds to builders someone else owns, such as a message bus's list of handlers.
  • A role is a workload: the components it requires.
  • A profile is the exact set of roles one process runs.
  • The host composes the profile it was started with, records which component registered each service, and refuses to start when a required component or configuration section is missing.
  • A test builds every declared profile.

The profile combined runs the roles orders and notifications; their components OrdersConsumer and NotificationsConsumer both require MessageProcessing, which is composed once

None of the pieces is new. Mark Seemann's Composition Root puts composition in one place near the entry point, and says only applications should have one. I keep the first part: the list of profiles is in one place. I break the second on purpose. Module projects reference the composition library, so their registrations sit with the code they register instead of in a host that references everything. ABP's modules are the same unit of registration, with dependencies between modules. Grafana Loki was one inspiration, among several systems that ship one binary able to run as any of its components; Loki picks them with -target. Spring Modulith does the module-verification side for Java, and Google's Service Weaver split one Go binary into processes until it was archived in 2025.

What I wanted beyond ABP's module graph was an owner for every registration and a test that builds every profile. I built that as Corfedo Troupe, an open-source .NET library, still in alpha. A component from its Messaging example:

public sealed class OrdersConsumer : IComponent
{
    public void Compose(IComponentBuilder component)
    {
        component.Requires<MessageProcessing>();
        component.Services(services => services.AddSingleton<OrderFormatter>());
        component.Contribute<WolverineOptions>(options =>
        {
            options.Discovery.IncludeType(typeof(PlaceOrderHandler));
            options.PublishMessage<PlaceOrder>().ToLocalQueue("orders");
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

MessageProcessing is composed once, however many components require it. The handler goes into Wolverine's discovery from the component that owns it, and the application turns conventional discovery off (one line in its Wolverine setup). A process that doesn't compose OrdersConsumer doesn't register PlaceOrderHandler. The mediator built its handler list from what an assembly contained; here the list comes from what the process composes.

Profiles name the processes. One executable runs as --profile combined on a laptop and as --profile orders and --profile notifications in separate deployments:

definition
    .Profile("orders", p => p.Role<OrdersRole>())
    .Profile("notifications", p => p.Role<NotificationsRole>())
    .Profile("combined", p => p.Role<OrdersRole>().Role<NotificationsRole>());
Enter fullscreen mode Exit fullscreen mode

A test calls CompositionVerifier.VerifyProfilesAsync, which builds every profile without starting it. In my current project, a profile missing a service now fails there, in CI, instead of after the image is running. The test catches what the components declare and what the container's own validation catches (ValidateOnBuild, ValidateScopes). A dependency resolved through a factory at runtime still gets past it. So does configuration: the test builds with its own settings, so a section missing in the deployed environment still stops the process, but before it listens and with the section named.

For the person running it, adding a slice is a component and maybe a role, and the test lists the profiles that no longer build before anyone deploys.

Adding the library didn't remove the problem

Moving registrations into components is mechanical work, and the over-registration moved with them. The shared helpers came along. One registered token validation the first time it was called and skipped every later call. Two components called it, so whichever ran first became the owner by accident. Another put an external API client into every process, because the component that called it was required by every role, including roles that never made that call.

Each process can now list what it composes and which component registered each service, and that list is where I found both. It showed token validation owned by whichever component happened to run first; the guard had hidden the second caller from the duplicate check. A service registered by two owners is listed as an advisory unless it is declared exclusive, and duplicate hosted services or options bindings stop startup. Before, the same facts were spread across branches.

Fixing them was the same work as without the library: decide which module owns token validation, split the helper that did three things, move the client into a component that only the processes using it require.

What I still write myself

Running as separate processes still takes code the library doesn't write. When the orders role needs the catalog and the catalog runs in another process, something has to make that call over HTTP, gRPC or a queue, carry the caller's identity and know the address. Troupe answers one question for that code: is the owner composed here? "Remote" only means "not here." The Operations example has HTTP/2 clients with mutual TLS between processes, and all of that code lives in the example.

Splitting also breaks things that worked combined: an in-memory cache two roles shared, a timer that should fire in one process, keys that must be the same everywhere. That needs its own post.

Boundaries are still projects and architecture tests. A component can register anything, and nothing in the composition stops the orders module from reaching into billing's internals.

One image has a cost. Every process ships the code of every slice, and they all come from one build. With one codebase and one release schedule that's fine. I'd expect it to hurt with two teams on different schedules.

Top comments (0)