In MediatR 14, what does AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>()) register, with which lifetimes, and when does it throw?
answer
- assembly scan for handler interfaces
- no assembly: ArgumentException
- handlers always Transient
- cfg.Lifetime covers IMediator, ISender, IPublisher
- RegisterGenericHandlers = false
basics
~10 sAddMediatR scans the assemblies you name for request, notification and stream handlers, registers them as transient, and adds IMediator, ISender and IPublisher at cfg.Lifetime, Transient by default. Called without any assembly, it throws ArgumentException.
solid answer
~40 sIn MediatR 14.2, `RegisterServicesFromAssemblyContaining<T>()` adds that type's assembly to the scan list; `AddMediatR` then looks for concrete classes closing `IRequestHandler<,>`, `IRequestHandler<>`, `INotificationHandler<>` and `IStreamRequestHandler<,>`. Request handlers go in with `TryAddTransient` (one per request type), notification handlers with `AddTransient` (all of them). Handlers are **always transient**; `cfg.Lifetime` (default `ServiceLifetime.Transient`) only applies to `IMediator`, `ISender`, `IPublisher` and a `NotificationPublisherType`. Open-generic request handlers are skipped unless `RegisterGenericHandlers = true`. With no assembly registered, it throws `ArgumentException("No assemblies found to scan...")`, which is exactly what the README's licence-key-only snippet does. Resolving `IMediator` also needs an `ILoggerFactory`; `WebApplication.CreateBuilder` provides one, a bare `ServiceCollection` in a test does not.
code
csharp · 6 linesbuilder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<PlaceOrderHandler>();
cfg.LicenseKey = builder.Configuration["MediatR:LicenseKey"];
// cfg.Lifetime stays Transient: it affects IMediator/ISender/IPublisher, not handlers
});go deeper
Recall that AddMediatR needs an assembly to scan, usually via RegisterServicesFromAssemblyContaining, and that it registers handlers plus IMediator, ISender and IPublisher.
Explain the registration details: which interfaces are scanned, TryAdd versus Add for request and notification handlers, handlers always transient, and what cfg.Lifetime really governs.
Diagnose the startup and test failures: the ArgumentException from a licence-only call, the missing ILoggerFactory in a bare container, and generic-handler limits blowing up on unconstrained parameters.
Weigh assembly scanning against explicit registration: scanning is convenient but hides what is wired, so decide how handlers are discovered across projects and how duplicates get caught in review.
## What the call does `services.AddMediatR(Action<MediatRServiceConfiguration>)` is MediatR's registration entry point for `Microsoft.Extensions.DependencyInjection`. It runs your lambda against a fresh `MediatRServiceConfiguration`, then does three things in order: applies the generic-handler limits, **scans** the registered assemblies, and adds the **required services** (the mediator, the publisher strategy, the licence services). `RegisterServicesFromAssemblyContaining<T>()`, `RegisterServicesFromAssemblyContaining(Type)`, `RegisterServicesFromAssembly(Assembly)` and `RegisterServicesFromAssemblies(params Assembly[])` all do the same thing: add assemblies to an internal list. Nothing is scanned until the lambda returns. ## What the scan finds The scan walks every type defined in those assemblies and keeps concrete (non-abstract, non-interface) classes that pass `cfg.TypeEvaluator` (default: every type) and close one of these interfaces: | Interface | Registered with | Effect | |---|---|---| | `IRequestHandler<TRequest, TResponse>` | `TryAddTransient` | one handler per request type; a second is silently ignored | | `IRequestHandler<TRequest>` | `TryAddTransient` | same, for requests with no result | | `INotificationHandler<TNotification>` | `AddTransient` | every handler is kept | | `IStreamRequestHandler<TRequest, TResponse>` | `TryAddTransient` | one handler per stream request | The scan also registers the exception-handler and exception-action interfaces, and pre/post processors when `AutoRegisterRequestProcessors` is on; those belong to the pipeline topic. Open-generic **notification** handlers (a `class AuditHandler<T> : INotificationHandler<T>`) are registered as open generics too. ## Lifetimes - **Handlers are always transient.** The registrar calls `AddTransient` / `TryAddTransient` directly; no setting changes that. - **`cfg.Lifetime`**, default `ServiceLifetime.Transient`, applies to `IMediator` (implemented by `cfg.MediatorImplementationType`, default `Mediator`), to `ISender` and `IPublisher` (factories that resolve `IMediator`), and to a publisher given as `NotificationPublisherType`. - The registrations use `TryAdd`, so an `IMediator` you registered earlier is not overwritten. `Mediator` resolves handlers from the `IServiceProvider` it was constructed with. Injected into an endpoint, that is the request's scope, so a handler's scoped dependencies are the request's own. ## When it throws 1. **No assembly registered** — `ArgumentException("No assemblies found to scan. Supply at least one assembly to scan for handlers.")`, at the `AddMediatR` call. The README's licence snippet, `services.AddMediatR(cfg => { cfg.LicenseKey = "..."; })`, does exactly that; set the key *alongside* an assembly registration. 2. **Generic handler limits exceeded** (only with `RegisterGenericHandlers = true`) — `ArgumentException` naming the limit, or `TimeoutException` when closing generics takes longer than `RegistrationTimeout`. 3. **No `ILoggerFactory`** — not at `AddMediatR`, but when the first `Mediator` is constructed: the licence services' factory throws `InvalidOperationException("MediatR requires ILoggerFactory to be registered...")`. An ASP.NET Core host always has logging; a hand-built `ServiceCollection` needs `services.AddLogging()`. ## Generic request handlers A class like `ArchiveHandler<TEntity> : IRequestHandler<Archive<TEntity>>` is skipped by default (`RegisterGenericHandlers = false`). Turned on, MediatR closes it over every concrete class in the scanned assemblies that satisfies the type parameter's constraints, bounded by: - `MaxGenericTypeParameters` = 10 - `MaxTypesClosing` = 100 candidate types per parameter - `MaxGenericTypeRegistrations` = 125,000 combinations - `RegistrationTimeout` = 15,000 ms Each limit is disabled by setting it to 0. An unconstrained type parameter matches every class in the assembly, so constrain it. ## A working Program.cs ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddMediatR(cfg => { cfg.RegisterServicesFromAssemblyContaining<PlaceOrderHandler>(); cfg.LicenseKey = builder.Configuration["MediatR:LicenseKey"]; }); ``` Point the scan at the assembly that holds the handlers (often an application-layer project, not the web project), and add one call per assembly when handlers are split across several. ## Other knobs on the configuration object - **`TypeEvaluator`** (`Func<Type, bool>`, default `t => true`) filters what the scan may register, for example to exclude handlers in a namespace used only by tests. - **`MediatorImplementationType`** swaps in a subclass of `Mediator`, typically one that overrides `PublishCore`. - **`NotificationPublisher`** and **`NotificationPublisherType`** choose the notification strategy; the default is `ForeachAwaitPublisher`. - Calling `AddMediatR` twice adds the second call's handlers, but `IMediator`, `ISender` and `IPublisher` keep the first registration because they go in with `TryAdd`; one call listing every assembly is easier to reason about.
- You set cfg.Lifetime = ServiceLifetime.Scoped. Are your MediatR handlers scoped now?No. `cfg.Lifetime` applies to `IMediator`, `ISender`, `IPublisher` and a `NotificationPublisherType`; the scan registers handlers with `AddTransient` or `TryAddTransient` regardless. To give one request handler another lifetime, register it yourself before `AddMediatR`: the scan's `TryAddTransient` then leaves your registration in place.
- Why does a unit test that builds a bare ServiceCollection with AddMediatR fail when it resolves IMediator?Constructing `Mediator` starts MediatR's licence check, whose services need an `ILoggerFactory`; without one their factory throws `InvalidOperationException` asking you to call `services.AddLogging()`. `WebApplication.CreateBuilder` registers logging, so the web app never sees it, but a hand-built container in a test must add it.
- How do you get MediatR to register ArchiveHandler<TEntity> : IRequestHandler<Archive<TEntity>>?Set `RegisterGenericHandlers = true`. MediatR then closes the handler over every concrete class in the scanned assemblies that satisfies `TEntity`'s constraints, within `MaxGenericTypeParameters` (10), `MaxTypesClosing` (100), `MaxGenericTypeRegistrations` (125,000) and `RegistrationTimeout` (15,000 ms). Exceeding one throws `ArgumentException` or `TimeoutException`, so constrain `TEntity` to the entity base type.
- AddMediatR scans the entry assembly automatically when no assembly is given.
- Setting cfg.Lifetime to Scoped makes every MediatR handler scoped.
- AddMediatR registers handlers as singletons for speed.
- Open-generic request handlers are picked up by the default scan.
- Two handlers for the same request make AddMediatR fail at startup.
Assumes MediatR 14.2: AddMediatR requires at least one assembly, scanned handlers are always transient, RegisterGenericHandlers defaults to false, and resolving the mediator needs an ILoggerFactory for the licence check.