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?
answer
- one entry point per concern
- this IServiceCollection, returns it
- this IEndpointRouteBuilder, works on groups too
- implementation types stay internal
- two lines to remove or move
basics
~20 sAddX 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 sEach 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 linesnamespace 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
Know that a module exposes an AddX method on IServiceCollection and a MapX method for its endpoints, and that Program.cs calls them.
Explain the signatures: this IServiceCollection returning it, this IEndpointRouteBuilder so groups work, and why that lets module classes stay internal.
Discuss duplicate registrations, per-module configuration sections, avoiding BuildServiceProvider, and where module-specific middleware or filters belong.
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.