skip to content

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%

answer

  1. IAsyncEnumerable<T>, not Task<List<T>>
  2. IStreamRequestHandler<TRequest, TResponse>
  3. async iterator with yield return
  4. [EnumeratorCancellation] on the token
  5. lazy until the first MoveNextAsync

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

solid answer

~40 s

A stream request implements `IStreamRequest<TResponse>`; its single handler implements `IStreamRequestHandler<TRequest, TResponse>` and returns `IAsyncEnumerable<TResponse>`, usually as an `async` iterator with `yield return` and a token marked `[EnumeratorCancellation]`. `ISender.CreateStream(request, ct)` is not awaited: it returns the sequence, and nothing (not even resolving the handler) happens until someone enumerates it, so a missing handler surfaces on the first `MoveNextAsync`. The win over `IRequest<List<T>>` is memory and time to first item: the handler can pass rows from EF Core's `AsAsyncEnumerable()` straight through, and a Minimal API endpoint can return the `IAsyncEnumerable<T>` so System.Text.Json writes the JSON array while enumerating. Stream requests have their own behaviour interface; ordinary pipeline behaviours do not wrap them.

code

csharp · 17 lines
csharp
public record GetRestaurantOrders(Guid RestaurantId, DateOnly Day) : IStreamRequest<OrderSummary>;

public class GetRestaurantOrdersHandler(TakeawayDbContext db)
    : IStreamRequestHandler<GetRestaurantOrders, OrderSummary>
{
    public async IAsyncEnumerable<OrderSummary> Handle(GetRestaurantOrders request,
        [EnumeratorCancellation] CancellationToken cancellationToken)
    {
        var orders = db.Orders
            .Where(o => o.RestaurantId == request.RestaurantId && o.Day == request.Day)
            .Select(o => new OrderSummary(o.Id, o.Total))
            .AsAsyncEnumerable();

        await foreach (var order in orders.WithCancellation(cancellationToken))
            yield return order;
    }
}

go deeper

for a junior

Recall the three pieces: an IStreamRequest<T> message, an IStreamRequestHandler returning IAsyncEnumerable<T>, and ISender.CreateStream, which you consume with await foreach.

for a middle

Explain the laziness: nothing runs until enumeration, the handler resolves on the first MoveNextAsync, and cancellation flows through [EnumeratorCancellation].

for a senior

Judge when streaming pays off (large exports, time to first item) and handle scope lifetime, mid-stream exceptions and client disconnects in an HTTP response.

for a principal

Decide whether streaming belongs in the mediator at all or directly in the endpoint, given that it brings its own behaviour interface and a different testing story.

## The three pieces MediatR has a third message shape beside requests and notifications: the **stream request**. - **`IStreamRequest<out TResponse>`**, a marker interface in `MediatR.Contracts`. The type argument is the *item* type, not a collection. - **`IStreamRequestHandler<in TRequest, out TResponse>`**, with one method, `IAsyncEnumerable<TResponse> Handle(TRequest request, CancellationToken cancellationToken)`. - **`ISender.CreateStream<TResponse>(IStreamRequest<TResponse> request, CancellationToken cancellationToken = default)`**, plus an `object` overload returning `IAsyncEnumerable<object?>`. Like an ordinary request, a stream request has **exactly one** handler: `AddMediatR` registers stream handlers with `TryAddTransient`, and MediatR resolves the handler with `GetRequiredService`. ## Lazy by construction `CreateStream` returns an `IAsyncEnumerable<T>` immediately. Internally the wrapper is itself an `async` iterator, so: 1. calling `CreateStream` validates the argument and fetches (or builds once) the cached wrapper for the request type, nothing more; 2. the handler is resolved and its `Handle` called when enumeration starts, at the first `MoveNextAsync` of an `await foreach`; 3. each item reaches the consumer as soon as the handler yields it; 4. if no handler is registered, the `InvalidOperationException` appears **on enumeration**. A test that only calls `CreateStream` passes even though the wiring is broken. ## Cancellation The token passed to `CreateStream` is handed to the handler's `Handle` and also applied with `WithCancellation` while MediatR enumerates. Mark the handler's token parameter with **`[EnumeratorCancellation]`** so that a token a consumer supplies through `WithCancellation` also reaches the iterator; the compiler warns about an async iterator whose `CancellationToken` parameter lacks it. ## Stream versus list | | `IRequest<List<T>>` + `Send` | `IStreamRequest<T>` + `CreateStream` | |---|---|---| | Handler returns | `Task<List<T>>` | `IAsyncEnumerable<T>` | | Memory | whole result buffered | one item at a time | | First item available | after the last one is loaded | as soon as it is yielded | | Consumer | `await` once | `await foreach` | | Pipeline | `IPipelineBehavior<,>` | its own stream behaviour interface | Choose the stream when the result set is large (an export, a day of orders for a busy restaurant), unbounded, or produced over time. Keep the list for small, bounded results: paging, counts and a `Results` type are simpler with a materialised list. ## In an ASP.NET Core endpoint A Minimal API handler can return the stream directly. System.Text.Json serialises an `IAsyncEnumerable<T>` as a JSON array while enumerating it, so the restaurant dashboard's order list is never fully held in memory on the server: ```csharp app.MapGet("/restaurants/{id:guid}/orders", (Guid id, DateOnly day, ISender sender, CancellationToken ct) => sender.CreateStream(new GetRestaurantOrders(id, day), ct)); ``` The `CancellationToken` parameter is bound to the request-aborted token, so a client that disconnects stops the handler's query at its next item. ## Things to watch - The handler's scoped dependencies, such as its `DbContext`, must stay alive until enumeration ends. Inside a request that holds, because the response is written within the request scope; a stream handed to a background task outlives that scope. - Exceptions thrown mid-stream reach the consumer at that item. In an HTTP response, the status code and part of the body may already be sent. - `CreateStream` does not return a `Task`; writing `await sender.CreateStream(...)` does not compile, because `IAsyncEnumerable<T>` is not awaitable. ## Consuming a stream outside HTTP In a background service or another handler, consume the stream with `await foreach`, passing the token either to `CreateStream` or through `WithCancellation`: ```csharp await foreach (var order in sender.CreateStream(new GetRestaurantOrders(id, day), ct)) { await exporter.WriteRowAsync(order, ct); } ``` Each iteration pulls one item from the handler, so a slow consumer slows the producer instead of letting a buffer grow. That back-pressure is the property a `List<T>` cannot give you. If the consumer needs everything in memory anyway (to sort it, count it or send it as one document) the stream buys nothing, and an ordinary request returning a list is the clearer choice.

  • Where does a missing MediatR stream handler surface?
    Not at `CreateStream`: the wrapper is an async iterator, so the handler is resolved with `GetRequiredService` when enumeration begins, and the `InvalidOperationException` appears on the first `MoveNextAsync`. A test that only calls `CreateStream` therefore passes; enumerate at least one item to prove the wiring.
  • Why mark the stream handler's CancellationToken with [EnumeratorCancellation]?
    MediatR passes the `CreateStream` token to `Handle` directly, but a consumer can also supply one through `WithCancellation`. The attribute tells the compiler to combine that token with the parameter inside the iterator; without it, a token given through `WithCancellation` is ignored and the compiler warns.

  • CreateStream must be awaited, just like Send.
  • The stream handler runs to completion when CreateStream is called.
  • A stream request's handler returns Task<IEnumerable<T>>.
  • IStreamRequest<T> takes the collection type, such as IStreamRequest<List<Order>>.
  • A stream request can have several handlers whose items are merged.