Clean&Reactoring Lesson 23 of 23

Lesson 23 of 23 · 8 min read · Updated

Modular Monolith in ASP.NET Core with IHostingStartup: Choose Your Modules at Startup

A modular monolith keeps module boundaries in the code, but lets you decide at deployment time how many processes run. ASP.NET Core already has what you need: IHostingStartup loads an assembly by name before your app starts, and IStartupFilter lets that assembly add its own middleware and endpoints. No extra NuGet package is required.

In this lesson you build a small parcel-shipping app out of four modules. The host never references a module type. One environment variable chooses the modules, so the same build runs as one process or as two. The idea comes from the Habr series by gandjustas on modular monoliths in ASP.NET (part 2). The scenario and code here are our own, and every command was run on .NET 10.

Technical Requirements

  1. .NET 10 SDK
  2. curl or the requests.http file in the sample
  3. Sample code: github.com/Fcakiroglu16/dotnetacademy, branch aspnet-modular-monolith

Core Concepts

  1. Module: a class library that uses the Microsoft.NET.Sdk.Web SDK with <OutputType>Library</OutputType>. It owns its endpoints and its service registrations.
  2. Contract: a small assembly with interfaces and records. Modules know each other only through contracts, never through implementations.
  3. **IHostingStartup**: the host reads the HostingStartupAssemblies setting (a semicolon-separated list, usually set with the HOSTINGSTARTUPASSEMBLIES environment variable), loads each assembly, finds [assembly: HostingStartup(typeof(T))] and calls T.Configure(IWebHostBuilder).
  4. **IStartupFilter**: wraps the request pipeline. A module uses it to add endpoints after the host pipeline is built.
  5. Topology: which modules run in which process. It becomes configuration, not a build decision.

The Plan

ProjectRole
Logistics.ContractsIShippingQuoteService, QuoteRequest, QuoteResult
Logistics.Quotes.Corethe price rule
Logistics.ModuleKitModuleBase
Logistics.Hostempty web host
Parcels moduleGET /parcels/{id}/quote, depends on the contract only
Quotes.Local modulecalculates the quote in-process
Quotes.Remote modulecalls another process over HTTP
Quotes.Api modulePOST /quotes, the other side of the remote call

Parcels needs a quote, but does not care where it is calculated. Quotes.Local and Quotes.Remote both implement the same interface, so choosing one of them is the whole deployment decision.

Step 1: The Contract

src/Logistics.Contracts/IShippingQuoteService.cs

namespace Logistics.Contracts;

public sealed record QuoteRequest(decimal WeightKg, int DistanceKm);

public sealed record QuoteResult(decimal Price, string Currency, string CalculatedBy);

public interface IShippingQuoteService
{
Task<QuoteResult> GetQuoteAsync(QuoteRequest request, CancellationToken ct = default);
}

Step 2: One Base Class for Every Module

ModuleBase is both the hosting startup and the startup filter. A module overrides only the hooks it needs.

src/Logistics.ModuleKit/ModuleBase.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Logistics.ModuleKit;

// One class is both the hosting startup (runs while the host is being built)
// and the startup filter (runs while the request pipeline is being built).
public abstract class ModuleBase : IHostingStartup, IStartupFilter
{
void IHostingStartup.Configure(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration(ConfigureAppConfiguration);
builder.ConfigureServices((ctx, services) =>
{
services.AddSingleton<IStartupFilter>(this);
ConfigureServices(ctx, services);
});
}

Action<IApplicationBuilder> IStartupFilter.Configure(Action<IApplicationBuilder> next) => app =>
{
next(app); // host pipeline first (it calls UseRouting)
Configure(app); // then this module's middleware and endpoints
};

protected virtual void ConfigureAppConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config) { }

protected virtual void ConfigureServices(WebHostBuilderContext ctx, IServiceCollection services) { }

protected virtual void Configure(IApplicationBuilder app) { }
}

Two details matter. The module registers itself as an IStartupFilter, so its pipeline code runs after the host's. And ModuleBase only uses ConfigureServices and ConfigureAppConfiguration on the web host builder. Calling IWebHostBuilder.Configure(app => ...) from a hosting startup would replace the host pipeline instead of extending it.

Step 3: A Host That Knows Nothing

src/Logistics.Host/Program.cs

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Modules map their endpoints after this point, so routing must already be in the pipeline.
app.UseRouting();

app.MapGet("/", (IConfiguration config) => new
{
pid = Environment.ProcessId,
modules = config["HostingStartupAssemblies"],
});

await app.RunAsync();

UseRouting() is explicit because module endpoints are mapped after it. The / endpoint only prints the setting, so you can see which modules this process loaded.

The project file references every module, but only so the build copies the DLLs next to the host. No host code uses a module type.

src/Logistics.Host/Logistics.Host.csproj

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<!-- Build-time only: these references copy the module DLLs next to the host.
No host code uses a module type. Which modules load is decided at startup. -->
<ItemGroup>
<ProjectReference Include="..\Modules\Parcels\Logistics.Module.Parcels.csproj" />
<ProjectReference Include="..\Modules\Quotes.Local\Logistics.Module.Quotes.Local.csproj" />
<ProjectReference Include="..\Modules\Quotes.Remote\Logistics.Module.Quotes.Remote.csproj" />
<ProjectReference Include="..\Modules\Quotes.Api\Logistics.Module.Quotes.Api.csproj" />
</ItemGroup>

</Project>

Step 4: The Modules

The Parcels module registers one endpoint and asks for the contract:

src/Modules/Parcels/ParcelsModule.cs

using Logistics.Contracts;
using Logistics.ModuleKit;
using Logistics.Module.Parcels;

[assembly: HostingStartup(typeof(ParcelsModule))]

namespace Logistics.Module.Parcels;

public sealed class ParcelsModule : ModuleBase
{
private static readonly Dictionary<int, QuoteRequest> Parcels = new()
{
[1] = new(WeightKg: 2.5m, DistanceKm: 120),
[2] = new(WeightKg: 18m, DistanceKm: 640),
};

protected override void Configure(IApplicationBuilder app) =>
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/parcels/{id:int}/quote", async (int id, IShippingQuoteService quotes, CancellationToken ct) =>
Parcels.TryGetValue(id, out var parcel)
? Results.Ok(await quotes.GetQuoteAsync(parcel, ct))
: Results.NotFound());
});
}

The in-process implementation registers itself in ConfigureServices:

src/Modules/Quotes.Local/LocalQuotesModule.cs

using Logistics.Contracts;
using Logistics.ModuleKit;
using Logistics.Module.Quotes.Local;
using Logistics.Quotes.Core;

[assembly: HostingStartup(typeof(LocalQuotesModule))]

namespace Logistics.Module.Quotes.Local;

public sealed class LocalQuotesModule : ModuleBase
{
protected override void ConfigureServices(WebHostBuilderContext ctx, IServiceCollection services) =>
services.AddSingleton<IShippingQuoteService, LocalQuoteService>();
}

internal sealed class LocalQuoteService : IShippingQuoteService
{
public Task<QuoteResult> GetQuoteAsync(QuoteRequest request, CancellationToken ct = default) =>
Task.FromResult(QuoteCalculator.Calculate(request));
}

The remote implementation reads the backend address from configuration and sends the same request over HTTP:

src/Modules/Quotes.Remote/RemoteQuotesModule.cs

using System.Net.Http.Json;
using Logistics.Contracts;
using Logistics.ModuleKit;
using Logistics.Module.Quotes.Remote;

[assembly: HostingStartup(typeof(RemoteQuotesModule))]

namespace Logistics.Module.Quotes.Remote;

public sealed class RemoteQuotesModule : ModuleBase
{
protected override void ConfigureServices(WebHostBuilderContext ctx, IServiceCollection services)
{
var baseUrl = ctx.Configuration["QuoteService:BaseUrl"]
?? throw new InvalidOperationException("QuoteService:BaseUrl is not configured.");

services.AddHttpClient<IShippingQuoteService, RemoteQuoteService>(c => c.BaseAddress = new Uri(baseUrl));
}
}

internal sealed class RemoteQuoteService(HttpClient client) : IShippingQuoteService
{
public async Task<QuoteResult> GetQuoteAsync(QuoteRequest request, CancellationToken ct = default)
{
using var response = await client.PostAsJsonAsync("/quotes", request, ct);
response.EnsureSuccessStatusCode();
return (await response.Content.ReadFromJsonAsync<QuoteResult>(ct))!;
}
}

Finally, the Quotes.Api module is the receiving end. It exposes the same price rule as POST /quotes:

src/Modules/Quotes.Api/QuotesApiModule.cs

using Logistics.Contracts;
using Logistics.ModuleKit;
using Logistics.Module.Quotes.Api;
using Logistics.Quotes.Core;

[assembly: HostingStartup(typeof(QuotesApiModule))]

namespace Logistics.Module.Quotes.Api;

public sealed class QuotesApiModule : ModuleBase
{
protected override void Configure(IApplicationBuilder app) =>
app.UseEndpoints(endpoints =>
endpoints.MapPost("/quotes", (QuoteRequest request) => Results.Ok(QuoteCalculator.Calculate(request))));
}

Step 5: Run Two Topologies

Topology A: one process. Load the parcels module and the local quote module:

HOSTINGSTARTUPASSEMBLIES="Logistics.Module.Parcels;Logistics.Module.Quotes.Local" \
dotnet run --project src/Logistics.Host --urls http://localhost:5200

Topology B: two processes, same build. The gateway swaps Quotes.Local for Quotes.Remote. A second instance of the same host runs only Quotes.Api:

scripts/run-split.sh

#!/usr/bin/env bash
# Topology B: same build, two processes. Gateway (5200) calls the quotes backend (5201) over HTTP.
set -euo pipefail
cd "$(dirname "$0")/.."

dotnet build src/Logistics.Host -v q
HOST_DLL=src/Logistics.Host/bin/Debug/net10.0/Logistics.Host.dll

HOSTINGSTARTUPASSEMBLIES="Logistics.Module.Quotes.Api" \
dotnet "$HOST_DLL" --urls http://localhost:5201 &
BACKEND_PID=$!
trap 'kill $BACKEND_PID' EXIT

HOSTINGSTARTUPASSEMBLIES="Logistics.Module.Parcels;Logistics.Module.Quotes.Remote" \
QuoteService__BaseUrl="http://localhost:5201" \
dotnet "$HOST_DLL" --urls http://localhost:5200

The responses from both topologies:

# A: one process (pid 61272)
GET /parcels/1/quote -> {"price":7.94,"currency":"EUR","calculatedBy":"pid 61272"}

# B: gateway pid 61289, backend pid 61288
GET /parcels/1/quote -> {"price":7.94,"currency":"EUR","calculatedBy":"pid 61288"}

The price is identical. Only calculatedBy changes, because the calculation moved to the backend process. ParcelsModule was not touched.

What Goes Wrong

We ran these cases on purpose:

SetupResult
Correct names in HOSTINGSTARTUPASSEMBLIESmodules load, endpoints answer
No variable at allhost starts, / returns "modules": null, /parcels/1/quote returns 404
Typo (Logistics.Module.Parcelz)one crit log: Startup assembly ... failed to execute, host still starts and answers /
Parcels loaded, no quote moduleevery request returns 500, even /, with Body was inferred but the method does not allow inferred body parameters
Quotes.Api not loaded, POST /quotes404

The last two rows are the price of this design. The compiler cannot see that Parcels needs a quote module, and a typo is only a log line. A startup check that every required contract has an implementation, or a health probe after deploy, closes that gap. Treat the module list as production configuration and review it like code.

Practical Rules

  1. Put every type that crosses a module boundary in a contracts assembly. If the host or another module uses a concrete module type, you lose the point of the design.
  2. Keep module startup code to ConfigureServices and ConfigureAppConfiguration. Do not call Configure(app => ...) on the web host builder.
  3. Build once and select modules with environment variables. Compose or Kubernetes then change topology without a rebuild.
  4. If you use MVC or Razor Pages, the Razor SDK discovers controllers from referenced assemblies at build time, so a disabled module can still register them. The source series covers the fix (GenerateMvcApplicationPartsAssemblyAttributes and AddApplicationPart in each module). This sample uses Minimal APIs, so it does not apply here.

Summary

  1. IHostingStartup plus IStartupFilter give you modules with no framework: each module owns its services and endpoints, and the host stays empty.
  2. A contract assembly lets you swap an in-process implementation for an HTTP one without touching the consumer.
  3. The same build ran as one process and as two, and the quote stayed 7.94 EUR for parcel 1.
  4. Missing modules fail quietly or late, so add a startup or deploy-time check for required contracts.