skip to content

Per-Module Registration

Modules inside one ASP.NET Core host, each exposing its own AddX and MapX extension methods, DbContext and internal types. Interviewers ask how boundaries are enforced and kept extractable.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

In an ASP.NET Core modular monolith, what do a module's AddX and MapX extension methods look like, and why should Program.cs call only those?

level: middleimportance: must knowfreq 45%

answer

  1. one entry point per concern
  2. this IServiceCollection, returns it
  3. this IEndpointRouteBuilder, works on groups too
  4. implementation types stay internal
  5. two lines to remove or move

basics

~20 s

AddX is a public static extension on IServiceCollection that registers the module's internal services, options and DbContext and returns the collection; MapX extends IEndpointRouteBuilder and maps its endpoints. Program.cs calls only these, so module internals stay hidden and movable.

solid answer

~40 s

Each module exposes two public entry points. `AddFeesModule(this IServiceCollection services, IConfiguration config)` registers everything the module needs: its handlers, its options bound from a `Fees` configuration section, its own `DbContext`. It returns `services` so calls chain. `MapFeesEndpoints(this IEndpointRouteBuilder app)` maps the module's endpoints, usually under one prefix such as `/fees`; extending `IEndpointRouteBuilder` rather than `WebApplication` means it works on the app and on a `RouteGroupBuilder`. Because those two methods live inside the module, every implementation class can be `internal`, and `Program.cs` reads as a list of modules: `AddAdmissionsModule`, `AddFeesModule`, `AddTimetablingModule`, then the matching `Map` calls. Removing a module is deleting two lines; extracting it is moving those two lines into a new host. It follows the framework's own convention of one `Add{Group}` method per feature, like `AddRazorComponents`.

code

csharp · 21 lines
csharp
namespace University.Fees;

public static class FeesModule
{
    public static IServiceCollection AddFeesModule(this IServiceCollection services, IConfiguration config)
    {
        services.Configure<FeesOptions>(config.GetSection("Modules:Fees"));
        services.AddDbContext<FeesDbContext>(o => o.UseNpgsql(config.GetConnectionString("university")));
        services.AddScoped<IssueInvoiceHandler>();
        services.AddScoped<IFeesModule, FeesModuleFacade>();
        return services;
    }

    public static IEndpointRouteBuilder MapFeesEndpoints(this IEndpointRouteBuilder app)
    {
        var fees = app.MapGroup("/fees").WithTags("Fees");
        fees.MapPost("/invoices", IssueInvoiceEndpoint.Handle);
        fees.MapGet("/students/{studentId:guid}/balance", GetBalanceEndpoint.Handle);
        return app;
    }
}

go deeper

for a junior

Know that a module exposes an AddX method on IServiceCollection and a MapX method for its endpoints, and that Program.cs calls them.

for a middle

Explain the signatures: this IServiceCollection returning it, this IEndpointRouteBuilder so groups work, and why that lets module classes stay internal.

for a senior

Discuss duplicate registrations, per-module configuration sections, avoiding BuildServiceProvider, and where module-specific middleware or filters belong.

for a principal

Use the two-method contract as the boundary you govern: what a module may register globally, and how the same calls move into a new host when a module is extracted.

## Modules as units of registration A **modular monolith** in ASP.NET Core is one host process whose code is split into modules that own their own features and data. For a university system, that means **Admissions**, **Fees** and **Timetabling** modules running in one `WebApplication`. The host still has a single `Program.cs`, a single DI container and a single endpoint table, so the question is how each module contributes to those without the host knowing the module's internals. The standard answer is two extension methods per module. ## The AddX method The ASP.NET Core documentation describes the framework convention: register a group of related services through one `Add{GroupName}` extension method, the way `AddRazorComponents` registers everything server-side rendering of Razor components needs. A module applies the same idea: - It is a `public static` method in a `public static` class, taking `this IServiceCollection services` plus whatever it needs, typically `IConfiguration`. - It registers the module's handlers, validators, background work and its `DbContext`, all of which can be `internal` because the method is in the same assembly. - It binds the module's own configuration section, for example `Modules:Fees`, so modules never read each other's settings. - It returns `services`, so `Program.cs` can chain module calls. The docs' example places such classes in the `Microsoft.Extensions.DependencyInjection` namespace so the method shows up without an extra `using`; teams that prefer explicit namespaces use the module's own instead. ## The MapX method The endpoint side mirrors it. `MapFeesEndpoints(this IEndpointRouteBuilder app)` creates the module's group with `app.MapGroup("/fees")`, applies shared conventions such as a tag or an authorization policy to the group, and maps each endpoint. Extending `IEndpointRouteBuilder` matters: `WebApplication` implements it and so does `RouteGroupBuilder`, so the host can mount the module at the root or under an outer group such as `/api`. ## Program.cs as a list of modules With both methods in place, `Program.cs` reads as an inventory: 1. Shared infrastructure: authentication, problem details, OpenAPI. 2. One `AddXModule` call per module. 3. `Build()`, then the middleware pipeline. 4. One `MapXEndpoints` call per module. That shape has three practical effects. The host cannot reach a module's internal types, because it never needs to. Deleting a module is deleting two lines and a project reference. And extracting a module into its own service starts with moving those same two calls into a new host's `Program.cs`. ## Dependencies between modules Modules are not fully independent: Timetabling needs to know which students Admissions has enrolled. The registration pattern keeps that dependency explicit and late-bound: 1. Admissions' `AddAdmissionsModule` registers the implementation of `IAdmissionsModule`, the interface in its public Contracts project. 2. Timetabling's handlers take `IAdmissionsModule` as a constructor parameter. Timetabling references only `University.Admissions.Contracts`. 3. Nothing is resolved during registration. The container connects the two when a Timetabling handler is first created, so the order of the `AddXModule` calls in `Program.cs` does not matter for resolving contracts (it still decides which duplicate registration wins). 4. In Development, `WebApplicationBuilder` turns on `ValidateOnBuild` and `ValidateScopes`, so a module that depends on a contract nobody registered fails at `Build()` instead of on the first request that needs it. The rule that falls out: an `AddX` method registers, it never resolves. ## Pitfalls interviewers probe | Pitfall | What goes wrong | Fix | |---|---|---| | Registering module internals in `Program.cs` | the host must see internal types, so they become `public` | keep every registration inside `AddXModule` | | Two modules both registering a shared service | duplicate registrations; the last one wins for single resolution | `TryAddScoped` and friends for shared services, or register shared ones once in the host | | Calling `BuildServiceProvider()` inside `AddX` to resolve something early | a second container with its own copies of singletons | use options, factories or `IServiceProvider` at resolution time | | `MapX` written against `WebApplication` | cannot be mounted under a route group | extend `IEndpointRouteBuilder` | | Modules reading each other's configuration sections | hidden coupling through settings | one section per module, bound inside its own `AddX` | ## Why interviewers ask The pattern is small, but it is where module boundaries are either enforced or quietly abandoned. A candidate who can explain why the methods are the only `public` types in the implementation assembly, and why `IEndpointRouteBuilder` rather than `WebApplication`, has usually maintained a modular codebase rather than read about one.

  • A module needs a piece of middleware of its own. Does that go in AddX?
    Usually not. `AddX` only sees `IServiceCollection`, before the app is built; it could register an `IStartupFilter` that injects middleware, but that hides pipeline order from the host. Prefer an endpoint filter or group convention applied inside `MapX`, so it runs only for that module's routes, or a `UseFeesModule(this IApplicationBuilder app)` method the host places explicitly.
  • Two modules both call services.AddScoped<IClock, SystemClock>(). What happens, and how do you avoid it?
    Both registrations are added. Resolving `IClock` returns the last one, and resolving `IEnumerable<IClock>` returns two instances, which can double-run anything enumerated. Shared services are either registered once by the host or registered with `TryAddScoped`, which skips the call when the service type is already registered.

  • Each module should build its own ServiceProvider inside AddX.
  • MapX should take WebApplication because only the app can map endpoints.
  • Program.cs should register each module's handlers so the wiring is visible in one place.
  • AddX must register module classes as public types for DI to construct them.
  • Middleware for a module belongs inside its AddX method.
open as a page

In an ASP.NET Core modular monolith on EF Core 10, why give each module its own DbContext and schema, and how do modules then read each other's data?

level: seniorimportance: must knowfreq 40%

basics

~20 s

A DbContext per module, with HasDefaultSchema and its own migrations history table, keeps each module's tables and migrations private and extractable. Other modules never query those tables; they call the owning module's public contract or keep their own copy updated by events.

open as a page

In an ASP.NET Core modular monolith, how would Admissions publish an ApplicantAdmitted event that Fees handles in-process, and what can go wrong?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Admissions defines ApplicantAdmitted in its Contracts project and publishes it through a dispatcher that resolves registered handlers from DI; Fees registers one. Dispatch runs inside the request, so a failing handler hits the caller and the modules commit separately.

open as a page

In an ASP.NET Core modular monolith, how do internal types and InternalsVisibleTo keep a module's implementation private while its tests can still reach it?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Mark everything in a module internal except its AddX and MapX methods and a small Contracts project of interfaces, DTOs and events. Other modules reference only Contracts. An InternalsVisibleTo item opens the internals to the module's own test project, nothing else.

open as a page

When would you extract the Timetabling module of a university's ASP.NET Core modular monolith into its own service, and what changes in its registration, data and cross-module calls?

level: principalimportance: should knowfreq 27%

basics

~20 s

Extract only for a concrete reason: scaling, release cadence, failure isolation or ownership. Then its AddX and MapX calls move into a new host, its schema becomes its own database, and callers keep its contract interface, now backed by a typed HttpClient.

open as a page

In an ASP.NET Core modular monolith, how can each module's Minimal API endpoints be discovered by assembly scanning, and what does scanning cost?

level: middleimportance: nice to knowfreq 22%

basics

~20 s

Each endpoint class implements a small IEndpoint interface with a MapEndpoint(IEndpointRouteBuilder) method; the module's AddX scans its assembly for those types and registers them, and MapX resolves them and calls MapEndpoint. Scanning trades explicit routes for reflection, trimming warnings and harder navigation.

open as a page