skip to content

Requests & Notifications

MediatR's two dispatch shapes: Send routes a request to exactly one handler, Publish fans a notification out to every handler. Interviewers ask what happens when one notification handler throws.

on this pageshow

explore

questions

6

With MediatR, how does ISender.Send differ from IPublisher.Publish, and how many handlers does each one expect?

level: juniorimportance: must knowfreq 72%

answer

  1. one request, one handler
  2. IRequest<TResponse> vs INotification
  3. zero notification handlers is fine
  4. missing request handler: InvalidOperationException
  5. IMediator inherits ISender and IPublisher

basics

~20 s

MediatR's Send delivers an IRequest<TResponse> to exactly one IRequestHandler and returns its response; Publish delivers an INotification to every registered INotificationHandler, possibly none, and returns a plain Task. ISender exposes Send, IPublisher exposes Publish, IMediator both.

solid answer

~30 s

`Send` is request/response: a `PlaceOrder : IRequest<OrderConfirmation>` goes to the single `IRequestHandler<PlaceOrder, OrderConfirmation>`, and `await sender.Send(command, ct)` returns its result. A request with no result implements plain `IRequest`, and its `IRequestHandler<PlaceOrder>` returns `Task`. MediatR resolves the handler with `GetRequiredService`, so a request with no registered handler fails with an `InvalidOperationException`. `Publish` is fan-out: an `OrderPlaced : INotification` reaches every `INotificationHandler<OrderPlaced>`, returns no value, and with zero handlers simply completes. The interfaces split the same way: `ISender` carries `Send` and `CreateStream`, `IPublisher` carries `Publish`, and `IMediator` inherits both, so an endpoint that only sends commands injects `ISender`.

code

csharp · 14 lines
csharp
public class PlaceOrderHandler(TakeawayDbContext db, IPublisher publisher)
    : IRequestHandler<PlaceOrder, OrderConfirmation>
{
    public async Task<OrderConfirmation> Handle(PlaceOrder request, CancellationToken ct)
    {
        var basket = await db.Baskets.SingleAsync(b => b.Id == request.BasketId, ct);
        var order = Order.FromBasket(basket, request.Postcode);
        db.Orders.Add(order);
        await db.SaveChangesAsync(ct);

        await publisher.Publish(new OrderPlaced(order.Id, order.RestaurantId), ct);
        return new OrderConfirmation(order.Id, EtaMinutes: 35);
    }
}

go deeper

for a junior

Recall the pairing: a request has exactly one handler and a result, a notification has any number of handlers and no result. Name IRequest, INotification and the handler interface for each.

for a middle

Explain what each call does when handlers are missing or duplicated: Send resolves one required handler and throws when absent, Publish resolves all handlers and treats none as fine.

for a senior

Show you know Publish is in-process and synchronous with the caller, that a silently shadowed duplicate request handler is a real bug, and why injecting ISender keeps dependencies honest.

for a principal

Frame Send versus Publish as a coupling decision: a notification hides who reacts, which helps independence but makes failure handling and ordering implicit, so use it where reactions are genuinely optional.

## Two dispatch shapes MediatR is an in-process dispatcher: you hand it a message object and it finds the class that handles that message type in the dependency injection container. It has two shapes of message, and the whole library is organised around the difference. - A **request** implements `IRequest<TResponse>` (or plain `IRequest` when nothing comes back). It is a command or query that **exactly one** handler answers. - A **notification** implements `INotification`. It is an event that **zero, one or many** handlers react to, and nobody returns anything. All three marker interfaces (plus `IStreamRequest<TResponse>`) live in the small `MediatR.Contracts` package, so a contracts project can declare messages without referencing the main `MediatR` package. ## Send: request/response `ISender.Send<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default)` returns `Task<TResponse>`. Inside, MediatR builds a wrapper for the request's runtime type and resolves `IRequestHandler<TRequest, TResponse>` from the service provider with **`GetRequiredService`**. Consequences: 1. If no handler is registered, the call fails with an **`InvalidOperationException`** from the container, at the moment you send, not at startup. 2. If the handler throws, the exception propagates to the caller of `Send` unchanged. 3. The handler's return value is the value of the awaited `Send`. A request with no result implements `IRequest`; its handler implements `IRequestHandler<TRequest>` and its `Handle` returns plain `Task`. The `Unit` struct still exists in `MediatR.Contracts` and the void wrapper uses it internally, but you do not declare `IRequest<Unit>` or return `Unit.Value` yourself. There is also `Send(object request, CancellationToken)`, which returns `Task<object?>` and finds the `IRequest<>` interface at run time; an object that implements neither `IRequest` nor `IRequest<T>` gets an `ArgumentException`. ## Publish: fan-out `IPublisher.Publish<TNotification>(TNotification notification, CancellationToken)` returns `Task`. MediatR resolves **all** `INotificationHandler<TNotification>` services with `GetServices`, removes duplicates of the same handler class, and hands the list to the configured `INotificationPublisher` (by default `ForeachAwaitPublisher`, which awaits them one after another). - **Zero handlers is not an error.** `GetServices` returns an empty sequence and `Publish` completes. - **Nothing comes back.** Handlers return `Task`; there is no aggregated result. - **Handler exceptions propagate** to the caller of `Publish`; how many handlers ran first depends on the publisher strategy. ## The three interfaces | Interface | Members | Inject it when | |---|---|---| | `ISender` | `Send` (three overloads), `CreateStream` (two overloads) | an endpoint or service only dispatches requests | | `IPublisher` | `Publish` (generic and `object`) | a handler or service only raises notifications | | `IMediator` | inherits `ISender` and `IPublisher`, adds nothing | the class genuinely needs both | `AddMediatR` registers `IMediator` against the `Mediator` class and registers `ISender` and `IPublisher` as factories that resolve `IMediator`, all at the configured lifetime (Transient by default). They are views of one implementation, not separate engines; injecting the narrow interface just documents intent and makes test doubles smaller. ## What happens under the hood `Mediator` keeps a static, per-type cache of small generic **wrapper** objects (one for each request, notification or stream type it has seen), so the reflection cost of building `RequestHandlerWrapperImpl<PlaceOrder, OrderConfirmation>` is paid once per process. The handlers themselves are **not** cached: every `Send` or `Publish` resolves them again from the `IServiceProvider` the mediator was constructed with. In an ASP.NET Core endpoint that provider is the request scope, so a handler that takes the application's `DbContext` gets the same instance the rest of the request uses. The `CancellationToken` you pass flows into the handler's `Handle(request, cancellationToken)`. In a Minimal API endpoint, a `CancellationToken` parameter is bound to the request-aborted token, so a client that disconnects can cancel the handler's database call. Forgetting to pass it is a common review comment: the handler then runs to completion for nobody. ## In the takeaway platform ```csharp public record PlaceOrder(Guid BasketId, string Postcode) : IRequest<OrderConfirmation>; public record OrderConfirmation(Guid OrderId, int EtaMinutes); public record OrderPlaced(Guid OrderId, Guid RestaurantId) : INotification; app.MapPost("/orders", async (PlaceOrder command, ISender sender, CancellationToken ct) => { var confirmation = await sender.Send(command, ct); return TypedResults.Created($"/orders/{confirmation.OrderId}", confirmation); }); ``` The `PlaceOrderHandler` saves the order and then calls `publisher.Publish(new OrderPlaced(...), ct)`; the kitchen-ticket, courier-dispatch and loyalty-points handlers each implement `INotificationHandler<OrderPlaced>` and know nothing about one another. ## Traps worth naming - Two classes implementing `IRequestHandler<PlaceOrder, OrderConfirmation>` do **not** fail at startup: the assembly scan registers request handlers with `TryAddTransient`, so the first one it registers wins and the other is silently unused. - `Publish` is not a message bus. It runs in the same process, inside the caller's `await`, with no persistence or retry. - Passing a request to `Publish(object)` or a notification to `Send(object)` compiles and fails at run time with `ArgumentException`.

  • What does a MediatR request with no result look like?
    The message implements non-generic `IRequest`, the handler implements `IRequestHandler<TRequest>` and its `Handle` returns `Task`, and the caller awaits `sender.Send(command, ct)` as a plain `Task`. `Unit` still exists in `MediatR.Contracts` for the internal wrapper, but you neither declare `IRequest<Unit>` nor return `Unit.Value`.
  • Two classes both implement IRequestHandler<PlaceOrder, OrderConfirmation>. What happens?
    Nothing fails. `AddMediatR` registers request handlers with `TryAddTransient`, so the first one the scan registers is the one `Send` resolves, and the other is ignored. Which one wins depends on scan order, so the bug shows up as wrong behaviour rather than an exception. Two notification handlers for the same notification, by contrast, are both registered and both run.
  • Can you send a request whose type is only known at run time?
    Yes: `ISender.Send(object request, CancellationToken)` returns `Task<object?>`. MediatR finds the request's `IRequest<>` interface by reflection, caches a wrapper per type, and dispatches. An object implementing neither `IRequest` nor `IRequest<T>` throws `ArgumentException`; `IPublisher.Publish(object)` does the same for a non-`INotification`.

  • Publish with no handlers throws, just like Send with no handler.
  • Send can fan one request out to several request handlers.
  • Publish returns the handlers' results as a list.
  • IMediator, ISender and IPublisher are separate implementations with different behaviour.
  • A request with no result must be declared IRequest<Unit> and return Unit.Value.
open as a page

With MediatR's default notification publisher, what happens when one of three OrderPlaced handlers throws, and how does TaskWhenAllPublisher change that?

level: seniorimportance: must knowfreq 58%

basics

~20 s

With the default ForeachAwaitPublisher, handlers run one after another; the first exception stops the remaining handlers and propagates out of Publish. TaskWhenAllPublisher starts every handler, so all of them run, and Publish then faults with their failures.

open as a page

In MediatR 14, what does AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>()) register, with which lifetimes, and when does it throw?

level: middleimportance: should knowfreq 50%

basics

~10 s

AddMediatR 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.

open as a page

In MediatR 14, where does the Lucky Penny licence key come from, and what happens at runtime when it is missing, invalid or expired?

level: seniorimportance: should knowfreq 40%

basics

~10 s

MediatR 14 reads the key from cfg.LicenseKey or Mediator.LicenseKey, then MEDIATR_LICENSE_KEY, then LUCKYPENNY_LICENSE_KEY. A missing, invalid or expired key never disables anything: MediatR only writes log entries under the LuckyPennySoftware.MediatR.License category.

open as a page

After MediatR moved to Lucky Penny's RPL-1.5-or-commercial licence, how would you decide whether a portfolio of ASP.NET Core services licenses it or replaces it?

level: principalimportance: should knowfreq 30%

basics

~20 s

Treat it as a licensing decision, not a code fix: MediatR 14 ships under RPL 1.5 or a paid Lucky Penny licence and only logs licence problems. Inventory what each service uses, then weigh licence cost against replacement effort.

open as a page

With MediatR, how do IStreamRequest<T> and ISender.CreateStream work, and when would you use them instead of an IRequest<List<T>>?

level: middleimportance: nice to knowfreq 20%

basics

~20 s

An IStreamRequest<T> is handled by one IStreamRequestHandler whose Handle returns IAsyncEnumerable<T>; ISender.CreateStream returns that sequence, and items flow as the handler yields them. Use it when results are large or arrive over time, instead of buffering a List<T>.

open as a page