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?
answer
- one class per endpoint
- a small IEndpoint interface
- Assembly.GetTypes plus IsAssignableTo
- TryAddEnumerable, then map in a loop
- IL2026 under trimming and Native AOT
basics
~20 sEach 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.
solid answer
~40 sThe team defines `interface IEndpoint { void MapEndpoint(IEndpointRouteBuilder app); }`, and every endpoint in a module, say `IssueInvoiceEndpoint`, implements it and maps one route. The module's `AddFeesModule` scans its own assembly with `typeof(FeesModule).Assembly.GetTypes()`, keeps concrete types that are assignable to `IEndpoint`, and registers them with `TryAddEnumerable(ServiceDescriptor.Transient(typeof(IEndpoint), type))`. `MapFeesEndpoints` creates the module's group, resolves `IEnumerable<IEndpoint>` and calls `MapEndpoint` on each, so a new endpoint is one new class. The costs: `Assembly.GetTypes` carries `[RequiresUnreferencedCode]`, so trimming and Native AOT report IL2026 and may remove the very types you scan for; startup does reflection work; and a reader can no longer find every route in one file. Explicit `Map` calls in `MapX` avoid all three and stay the simpler default.
code
csharp · 25 linespublic interface IEndpoint
{
void MapEndpoint(IEndpointRouteBuilder app);
}
internal static class EndpointScanning
{
public static IServiceCollection AddEndpointsFrom(this IServiceCollection services, Assembly assembly)
{
var descriptors = assembly.GetTypes()
.Where(t => t is { IsAbstract: false, IsInterface: false } && t.IsAssignableTo(typeof(IEndpoint)))
.Select(t => ServiceDescriptor.Transient(typeof(IEndpoint), t));
services.TryAddEnumerable(descriptors);
return services;
}
public static IEndpointRouteBuilder MapEndpointsFrom(this IEndpointRouteBuilder group, Assembly assembly)
{
foreach (var endpoint in group.ServiceProvider.GetServices<IEndpoint>()
.Where(e => e.GetType().Assembly == assembly))
endpoint.MapEndpoint(group);
return group;
}
}go deeper
Know that Minimal API endpoints are not discovered automatically the way controllers are, so something must call Map for each one.
Explain the IEndpoint convention: scan with GetTypes, register with TryAddEnumerable, then map the module's own endpoints in a loop on its group.
Name the costs: IL2026 and trimmed types under Native AOT, cross-module leakage without a per-module marker, and lost navigability.
Set the team rule on explicit mapping versus scanning, given AOT plans and how often route lists cause merge conflicts.
## Why teams scan for endpoints In a module with dozens of Minimal API endpoints, `MapFeesEndpoints` turns into a long list of `MapGet` and `MapPost` lines that every developer edits, and forgetting a line means a feature silently has no route. **Endpoint scanning** replaces the list with a convention: every endpoint class declares its own route, and the module discovers them at startup. ## The convention 1. Define a tiny interface in a shared project: `public interface IEndpoint { void MapEndpoint(IEndpointRouteBuilder app); }`. 2. Each endpoint class implements it and maps exactly one route, for example `IssueInvoiceEndpoint` maps `POST /invoices` and points at its own static handler method. 3. The module's `AddX` method scans **its own** assembly for concrete `IEndpoint` implementations and registers each one. 4. The module's `MapX` method creates the module's route group, resolves the registered `IEndpoint` instances, keeps those from its own assembly (every module's endpoints share one container) and calls `MapEndpoint(group)` on each. The registration uses `TryAddEnumerable`, which adds a `ServiceDescriptor` for `IEndpoint` only if that exact implementation type is not already registered, so scanning twice does not map a route twice. ## Scoping the scan to a module Scanning must stay inside module boundaries. If one central method scans every loaded assembly, the host decides which endpoints exist and every endpoint lands in one flat route table. Scanning per module, from inside `AddFeesModule`, keeps each module responsible for its own routes, lets each module mount under its own group (`/fees`, `/admissions`), and lets the endpoint classes stay `internal`, since the scanning code is in the same assembly. Libraries exist that add assembly-scanning helpers to `IServiceCollection`; that general topic belongs with DI containers. The hand-written version is a dozen lines and keeps the convention visible. ## What scanning costs | Cost | Why | Mitigation | |---|---|---| | Trimming and Native AOT warnings | `Assembly.GetTypes()` is annotated `[RequiresUnreferencedCode("Types might be removed")]`, so the trimmer reports **IL2026** | do not scan in trimmed or AOT apps; map explicitly | | Types removed by the trimmer | an endpoint class referenced only by reflection can be trimmed away | explicit references, or keep scanning out of AOT builds | | Startup work | reflection over every type in the assembly | negligible for most apps, measurable in very large ones | | Navigation | no single file lists the module's routes | the OpenAPI document or a route list at startup | | Ordering | discovery order is not a contract | do not rely on order between endpoints | The first two are the ones interviewers press on. Native AOT already needs the Request Delegate Generator for Minimal APIs, and reflection-based discovery cuts against the whole point of an ahead-of-time compiled app. For a module that will be published with `PublishAot`, explicit mapping is the honest choice. ## Keeping routes discoverable The usual complaint about scanning is "where is this route defined?". Two cheap answers: - Name endpoint classes after their use case and keep each next to its handler, so searching for `IssueInvoice` finds the route. - In Development, list what was actually mapped. Routing registers a singleton `EndpointDataSource`; after `MapXEndpoints` has run, its `Endpoints` collection holds every endpoint with its route pattern and metadata, which can be logged once at startup. The OpenAPI document gives the same inventory to anyone reading the API from outside. ## Scanning or explicit mapping - **Explicit `Map` calls in `MapX`**: everything visible in one method, trim-safe, a compile error if a handler is removed. The cost is one line per endpoint. - **Scanning**: one class per endpoint and no central list to edit, at the cost of reflection and AOT incompatibility. Many teams start explicit and switch to scanning only when a module's route list becomes a merge-conflict hot spot. Either way the convention lives inside the module, which is what keeps it a per-module concern rather than a host-wide one.
- Why does MapEndpointsFrom filter the resolved IEndpoint instances by assembly?Every module registers its endpoints as `IEndpoint` in the same container, so resolving `IEnumerable<IEndpoint>` returns all of them. Without the filter, `MapFeesEndpoints` would also map Admissions' and Timetabling's endpoints under `/fees`. Filtering by the module's assembly, or using a per-module marker interface, keeps each module mapping only its own classes under its own group.
- Why does the scanning code call TryAddEnumerable instead of AddTransient?`TryAddEnumerable` skips a descriptor whose service and implementation type pair is already registered, so calling the scan twice, or from two places, does not register an endpoint class twice and map the same route twice, which would make routing fail with an ambiguous match.
- ASP.NET Core discovers Minimal API endpoints automatically, like controllers.
- Assembly scanning is fully compatible with trimming and Native AOT.
- Scanning every loaded assembly from Program.cs is the cleanest module design.
- Registering with AddTransient twice is harmless because routes are deduplicated.