Without MediatR - Streams and AsyncEnumerables

Arialdo Martini — 29/08/2023 — C# MediatR

Request/response, Streams and AsyncEnumerables

With MediatR

MediatR requires you to use a special type for the request, and a special one for the request handler:

record StreamRequest : IStreamRequest<string>;}

class StreamHandler : IStreamRequestHandler<StreamRequest, string>
{
    public async IAsyncEnumerable<string> Handle(StreamRequest request, CancellationToken cancellationToken)
    {
        yield return "foo";
        yield return "bar";
    }
}

code

Without MediatR

With plain OOP, there’s nothing special to change, other than returning an IAsyncEnumerable of results. The rest is already natively supported by C#:

interface IStreamHandler
{
    IAsyncEnumerable<string> Ping();
}

class StreamHandler : IStreamHandler
{
    async IAsyncEnumerable<string> IStreamHandler.Ping()
    {
        yield return "foo";
        yield return "bar";
    }
}

code

FAQs

Which approach is preferrable?

Answer
Just like for Requests not returning any value, MediatR requires a special type for stream requests and another special one for their handlers, while the native C# OOP does not need any special treatment and works out-of-the-box.

Comments

GitHub Discussions