Blazingly fast, convention-based C# mediator powered by source generators and interceptors.
- π Near-direct call performance - Zero runtime reflection, minimal overhead
- β‘ Convention-based - No interfaces or base classes required
- π§ Full DI support - Microsoft.Extensions.DependencyInjection integration
- π§© Plain handler classes - Drop in static or instance methods anywhere
- πͺ Middleware pipeline - Before/After/Finally hooks with state passing
- π― Built-in Result<T> - Rich status handling without exceptions
- π Tuple returns - Automatic cascading messages
- π Compile-time safety - Early validation and diagnostics
- π§ͺ Easy testing - Plain objects, no framework coupling
- π Superior debugging - Short, simple call stacks
Traditional mediator libraries force you into rigid interface contracts like IRequestHandler<TRequest, TResponse>. This means:
- One handler class per message type
- Fixed method signatures
- Always async (even for simple operations)
- Lots of boilerplate
Foundatio Mediator's conventions give you freedom:
public class OrderHandler
{
// Sync handler - no async overhead
public decimal Handle(CalculateTotal query) => query.Items.Sum(i => i.Price);
// Async with any DI parameters you need
public async Task<Order> HandleAsync(GetOrder query, IOrderRepo repo, CancellationToken ct)
=> await repo.FindAsync(query.Id, ct);
// Cascading: first element returned, rest auto-published as events
public (Order order, OrderCreated evt) Handle(CreateOrder cmd) { /* ... */ }
}
// Static handlers for maximum performance
public static class MathHandler
{
public static int Handle(Add query) => query.A + query.B;
}Prefer explicit interfaces? Use
IHandlermarker interface or[Handler]attributes instead. See Handler Conventions.
dotnet add package Foundatio.Mediator// Program.cs
services.AddMediator();// Messages (records, classes, anything)
public record GetUser(int Id);
public record CreateUser(string Name, string Email);
public record UserCreated(int UserId, string Email);
// Handlers - just plain classes ending with "Handler" or "Consumer"
public class UserHandler
{
public async Task<Result<User>> HandleAsync(GetUser query, IUserRepository repo)
{
var user = await repo.FindAsync(query.Id);
return user ?? Result.NotFound($"User {query.Id} not found");
}
public async Task<(User user, UserCreated evt)> HandleAsync(CreateUser cmd, IUserRepository repo)
{
var user = new User { Name = cmd.Name, Email = cmd.Email };
await repo.AddAsync(user);
// Return tuple: first element is response, rest are auto-published
return (user, new UserCreated(user.Id, user.Email));
}
}
// Event handlers
public class EmailHandler
{
public async Task HandleAsync(UserCreated evt, IEmailService email)
{
await email.SendWelcomeAsync(evt.Email);
}
}
// Middleware - classes ending with "Middleware"
public class LoggingMiddleware(ILogger<LoggingMiddleware> logger)
{
public Stopwatch Before(object message) => Stopwatch.StartNew();
// Objects or tuples returned from the Before method are available as parameters
public void Finally(object message, Stopwatch sw, Exception? ex)
{
logger.LogInformation("Handled {MessageType} in {Ms}ms",
message.GetType().Name, sw.ElapsedMilliseconds);
}
}// Query with response
var result = await mediator.InvokeAsync<Result<User>>(new GetUser(123));
if (result.IsSuccess)
Console.WriteLine($"Found user: {result.Value.Name}");
// Command with automatic event publishing
var user = await mediator.InvokeAsync<User>(new CreateUser("John", "john@example.com"));
// UserCreated event automatically published to EmailHandler
// Publish events to multiple handlers
await mediator.PublishAsync(new UserCreated(user.Id, user.Email));Key topics:
- Getting Started - Step-by-step setup
- Handler Conventions - Discovery rules and patterns
- Middleware - Pipeline hooks and state management
- Result Types - Rich status handling
- Performance - Benchmarks vs other libraries
- Configuration - MSBuild and runtime options
For debugging purposes, you can inspect the source code generated by Foundatio Mediator. Add this to your .csproj:
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Remove="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
<Content Include="$(CompilerGeneratedFilesOutputPath)/**/*.cs" />
</ItemGroup>After building, check the Generated folder for handler wrappers, DI registrations, and interceptor code. See Troubleshooting for more details.
Want the latest CI build before it hits NuGet? Add the Feedz source (readβonly public) and install the pre-release version:
dotnet nuget add source https://f.feedz.io/foundatio/foundatio/nuget -n foundatio-feedz
dotnet add package Foundatio.Mediator --prereleaseOr add to your NuGet.config:
<configuration>
<packageSources>
<add key="foundatio-feedz" value="https://f.feedz.io/foundatio/foundatio/nuget" />
</packageSources>
<!-- Optional: limit this source to Foundatio packages -->
<packageSourceMapping>
<packageSource key="foundatio-feedz">
<package pattern="Foundatio.*" />
</packageSource>
</packageSourceMapping>
</configuration>CI builds are published with pre-release version tags (e.g. 1.0.0-alpha.12345+sha.abcdef). Use them to try new features earlyβavoid in production unless you understand the changes.
Contributions are welcome! Please feel free to submit a Pull Request. See our documentation for development guidelines.
@martinothamar/Mediator was the primary source of inspiration for this library, but we wanted to use source interceptors and be conventional rather than requiring interfaces or base classes.
Other mediator and messaging libraries for .NET:
- MediatR - Simple, unambitious mediator implementation in .NET with request/response and notification patterns
- MassTransit - Distributed application framework for .NET with in-process mediator capabilities alongside service bus features
MIT License