Every time I started a project with MediatR, I spent the first days writing the same code again: a result type, validation, caching and the registration glue around them. Then MediatR announced it was going commercial. That was the push to build Vitreous, my first open-source project: a mediator for .NET that does its wiring at compile time instead of at startup.

The code I kept rewriting

A mediator is a small idea. You send a command or a query, and it finds the one handler for it. The library itself was never the problem. The problem was everything I had to add before it fit the way I like to build:

  • A Result type, so handlers return errors instead of throwing exceptions for normal failures.
  • Validation that runs before the handler.
  • Caching for queries.
  • Registration code to wire every handler into dependency injection.

So Vitreous ships with those pieces built in: a Result<T> and Error type (including validation errors with per-field messages), pipeline behaviors for things like validation and logging, and caching. A handler returns a Result<T>, and a plain value or an Error converts to it on its own:

CreateOrderHandler.cs

public sealed record CreateOrderCommand(string Customer) : ICommand<Guid>; public sealed class CreateOrderHandler : ICommandHandler<CreateOrderCommand, Guid> { public ValueTask<Result<Guid>> Handle(CreateOrderCommand command, CancellationToken ct = default) { if (string.IsNullOrWhiteSpace(command.Customer)) return new(Error.Validation("Customer is required.")); return new(Guid.NewGuid()); } } 

Caching (with a Redis backend) and a small developer dashboard with live traces are separate packages, so a project only pulls in what it uses.

Why a source generator

Most mediators find handlers with reflection: at startup they scan your assemblies, look for types that implement the handler interfaces and register them one by one. It works, but you pay for it on every start, and a mistake such as a command with no handler only shows up at runtime.

A source generator moves that work to the build. It was my first time writing one, so the first step was understanding how Roslyn's incremental generators actually work. Once it clicked, the generator could see every handler in the project while it compiled and write the registration code for me. The AddVitreousHandlers() you call in Program.cs doesn't exist in the library. It's generated in your project, and it registers each handler directly:

Generated (simplified)

public static IServiceCollection AddVitreousHandlers(this IServiceCollection services) { var lifetime = ServiceLifetime.Singleton; // from VitreousOptions services.TryAdd(new ServiceDescriptor( typeof(ICommandHandler<CreateOrderCommand, Guid>), typeof(CreateOrderHandler), lifetime)); services.TryAdd(new ServiceDescriptor( typeof(IQueryHandler<GetOrderQuery, OrderDto>), typeof(GetOrderHandler), lifetime)); // ...one registration per handler, no scanning return services; } 

Dispatch works the same way. Instead of building handler types with reflection at runtime, the generated dispatcher is a plain chain of type checks, one per message.

The part I didn't expect to like this much is the compile-time errors. If a command has no handler, the build tells you:

warning VIT001: No handler is registered for 'CreateOrderCommand'. 

Two handlers for the same command is VIT002, an error. Those are bugs I used to find in a running app.

The numbers

I benchmarked Vitreous against MediatR with BenchmarkDotNet on .NET 9 (Ryzen 7 7800X3D). The full tables are in the repository.

Scenario MediatR Vitreous
Startup (build DI container) 37,404 ns / 106 KB 1,191 ns / 7.5 KB
Send a query 64.9 ns / 264 B 57.9 ns / 64 B
Publish a notification 88.8 ns / 288 B 63.6 ns / 0 B
Stream query, 10 items 376.4 ns / 512 B 201.1 ns / 184 B

To be honest about it: a single dispatch is a few nanoseconds either way, and nobody's API is slow because of its mediator. The real differences are startup, about 31 times faster with 14 times less allocated, and allocations on the hot path. Publishing a notification allocates nothing.

The bug only a real install could find

Everything passed in the repository: unit tests, generator tests, the sample apps. Then I added Vitreous from NuGet to a private project, the first real integration, and nothing worked: not a single handler was registered.

The generator had never run. I had packed it under lib/netstandard2.0/, where NuGet puts normal libraries, but the compiler only loads analyzers and generators from analyzers/dotnet/cs/. So the generated AddVitreousHandlers() never existed, and the call quietly bound to the reflection overload instead, with no assemblies to scan. It registered nothing and said nothing.

Inside the repository the generator is referenced as a project, not as a package, so the tests never saw it. The fix in 0.1.1 was a few lines in the .csproj:

Vitreous.SourceGeneration.csproj

<PropertyGroup> <IncludeBuildOutput>false</IncludeBuildOutput> <DevelopmentDependency>true</DevelopmentDependency> </PropertyGroup> <ItemGroup> <None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" /> </ItemGroup> 

Two more changes made sure it can't happen quietly again. Calling AddVitreousHandlers() with no generator and no assemblies now throws with a message that explains both options. And CI unpacks the package on every build and checks that the generator is in the right folder.

The same release fixed a handful of other generator bugs, like notification handlers being dropped and VIT001 never firing for record messages. The lesson I took: test the package people install, not just the project you build.

What I'd do differently, and what's next

Vitreous is opinionated. It assumes you want results instead of exceptions, and it brings caching and a dashboard along. That might be a bit much for some projects, but it's how I like to build, and that was the point.

Next, I want it to cover more of the setup a clean architecture project needs, so it becomes the one package you install at the start instead of the five you wire together.

It's on GitHub and NuGet, MIT licensed. If you try it, I'd like to hear what's missing.

Originally published on domduva.com.