Skip to main content

The Mediator pattern with MassTransit

For years, when a .NET developer said "I need the mediator pattern," the answer was almost automatically MediatR. Jimmy Bogard's library became the default so quickly that a lot of teams never really questioned it, they just added the NuGet package and moved on.

That changed in 2025. MediatR moved to a commercial license, and suddenly "just add MediatR" wasn't a free decision anymore. That's a good moment to take a step back and look at what the mediator pattern actually is, and to point out something a lot of developers overlook: if you're already using MassTransit in your project, you already have a mediator implementation available. No extra package, no extra license to think about.

Remark: Be aware that MassTransit switched to a commercial license as well starting from version 9.

What is the mediator pattern?

The mediator pattern is about decoupling the sender of a request from the thing that handles it. Instead of a controller or service directly calling into a handler class, it sends a message to a mediator, and the mediator figures out which handler should process it.

The benefit: your calling code doesn't need to know about the handler's dependencies, its constructor, or even which assembly it lives in. You send a command or a request, and the mediator dispatches it. This is especially useful in a CQRS-style setup, where you want a thin API layer that just sends commands and queries without wiring up every handler by hand.

MediatR popularized this for in-process messaging in .NET. But the pattern itself doesn't require MediatR, it's just an interface (Send, Publish) and some dispatch logic behind it. And that's exactly what MassTransit's mediator gives you.

Two ways to get there

If you're starting from scratch, adding MediatR is still the most well-known route. But if MassTransit is already part of your stack (and for a lot of message-driven .NET systems, it is), you're pulling in a second in-process messaging abstraction that does almost the same thing your existing library can already do.

MassTransit ships with an in-memory mediator implementation, built on the same consumer model you already use for your bus. No transport, no broker, everything runs in-process, but you get the same IConsumer<T> shape you're used to from regular MassTransit consumers.

Remark: this is a meaningful mental shift if you're coming from MediatR. MediatR is handler-based: you implement IRequestHandler<TRequest, TResponse>. MassTransit's mediator is consumer-based: you implement IConsumer<T>, the same interface you'd use for a real bus consumer. That consistency is actually the whole point, your in-process and out-of-process messaging code looks the same.

Setting it up

Add the mediator in your service registration:

builder.Services.AddMediator(cfg =>
{
    cfg.AddConsumer<SubmitOrderConsumer>();
    cfg.AddConsumer<GetOrderStatusConsumer>();
});

Define your message contract like you would for any MassTransit message:

public record SubmitOrder
{
    public Guid OrderId { get; init; }
    public Guid CustomerId { get; init; }
}

And a consumer to handle it:

public class SubmitOrderConsumer : IConsumer<SubmitOrder>
{
    public async Task Consume(ConsumeContext<SubmitOrder> context)
    {
        var order = context.Message;

        // handle the command
    }
}

To send the command from a controller or minimal API endpoint, inject IMediator:

app.MapPost("/orders", async (SubmitOrder command, IMediator mediator) =>
{
    await mediator.Send(command);
    return Results.Accepted();
});

Request/response

Fire-and-forget commands are only half the story. If you need a response, MassTransit's mediator supports the request/response pattern too, using a request client created from IMediator:

public class GetOrderStatusConsumer : IConsumer<GetOrderStatus>
{
    public async Task Consume(ConsumeContext<GetOrderStatus> context)
    {
        await context.RespondAsync(new OrderStatusResult
        {
            OrderId = context.Message.OrderId,
            Status = "Processing"
        });
    }
}
var client = mediator.CreateRequestClient<GetOrderStatus>();
var response = await client.GetResponse<OrderStatusResult>(new GetOrderStatus { OrderId = orderId });

Same request/response shape you'd use with a real bus, just resolved in-process.

Remark: MassTransit dispatches asynchronously under the hood, but Send only completes once the consumer's Consume method completes. If the consumer throws, the exception propagates back to the caller, so your normal error handling around Send/GetResponse still works the way you'd expect.

Scoped vs singleton

IMediator is registered as a singleton, and by default each consumer gets its own DI scope. If you need several consumers in a pipeline to share the same scope (think: sharing a DbContext across steps), inject IScopedMediator instead. No extra configuration needed, it's available as soon as you've called AddMediator().

Do you lose anything?

Middleware like UseMessageRetry and UseInMemoryOutbox works with the mediator too, so you're not giving up MassTransit's pipeline behaviors just because you're not going over a transport. What you don't get: routing slip activities aren't supported through the mediator, but consumers, handlers, and sagas (including saga state machines) are fully supported.

If your project doesn't use MassTransit for anything else, MediatR (or a small hand-rolled mediator, plenty of examples of that around too) is still a reasonable choice. But if MassTransit is already in your dependency tree, you're one AddMediator() call away from not needing a second library for the same job.

That's it!

More information

Popular posts from this blog

Podman– Command execution failed with exit code 125

After updating WSL on one of the developer machines, Podman failed to work. When we took a look through Podman Desktop, we noticed that Podman had stopped running and returned the following error message: Error: Command execution failed with exit code 125 Here are the steps we tried to fix the issue: We started by running podman info to get some extra details on what could be wrong: >podman info OS: windows/amd64 provider: wsl version: 5.3.1 Cannot connect to Podman. Please verify your connection to the Linux system using `podman system connection list`, or try `podman machine init` and `podman machine start` to manage a new Linux VM Error: unable to connect to Podman socket: failed to connect: dial tcp 127.0.0.1:2655: connectex: No connection could be made because the target machine actively refused it. That makes sense as the podman VM was not running. Let’s check the VM: >podman machine list NAME         ...

Cache stampede: when our cache turned against us

While investigating some performance issues, we ran into an ASP.NET Core API that cached a fairly expensive aggregation query for 60 seconds. Under normal load, that was fine: one request rebuilds the cache, everyone else reads from it. Under peak load, dozens of requests would arrive in that same expiry window, all see a cache miss, and all fire the same expensive query in parallel. The database didn't like that. That was the moment when our caching layer stopped helping and started hurting. A burst of requests comes in at the same time, all miss the cache, and all go hammer the database or the downstream API at once. That's a cache stampede . The cache was supposed to protect our backend, and for a few hundred milliseconds it did the opposite. Why this happens IMemoryCache.GetOrCreate (and its async sibling) looks like it protects you, but it doesn't add any locking on its own. Look at the naive version: public async Task<Report> GetReportAsync(string key) ...

VS Code Planning mode

After the introduction of Plan mode in Visual Studio , it now also found its way into VS Code. Planning mode, or as I like to call it 'Hannibal mode', extends GitHub Copilot's Agent Mode capabilities to handle larger, multi-step coding tasks with a structured approach. Instead of jumping straight into code generation, Planning mode creates a detailed execution plan. If you want more details, have a look at my previous post . Putting plan mode into action VS Code takes a different approach compared to Visual Studio when using plan mode. Instead of a configuration setting that you can activate but have limited control over, planning is available as a separate chat mode/agent: I like this approach better than how Visual Studio does it as you have explicit control when plan mode is activated. Instead of immediately diving into execution, the plan agent creates a plan and asks some follow up questions: You can further edit the plan by clicking on ‘Open in Editor’: ...