Skip to main content
.NETStandard2.0

A fast, convention-based C# mediator library using incremental source generators

Published
Mar 4, 2026
7mo ago
Total Downloads
22.4K
22,447

Install

dotnet add package Foundatio.Mediator --version 1.0.0-rc.12
ProductVersions
.NET Standard
netstandard2.0

README

FoundatioFoundatio

Build status NuGet Version feedz.io Discord

Build completely message-oriented, loosely coupled .NET apps that are easy to test β€” with near-direct-call performance and zero boilerplate. Powered by source generators and interceptors.

✨ Why Choose Foundatio Mediator?

  • πŸš€ Near-direct call performance β€” zero runtime reflection, minimal overhead (benchmarks)
  • ⚑ Convention-based β€” no interfaces or base classes required
  • 🌐 Auto-generated endpoints β€” Minimal API endpoints from handlers, skip the mapping boilerplate
  • 🎯 *Built-in Result* β€” rich status handling without exceptions, auto-mapped to HTTP status codes
  • πŸŽͺ Middleware pipeline β€” Before/After/Finally/Execute hooks with state passing
  • πŸ”„ Cascading messages β€” tuple returns auto-publish events
  • 🧩 Plain handler classes β€” static or instance methods, any signature
  • πŸ”§ Full DI support β€” Microsoft.Extensions.DependencyInjection integration
  • πŸ”’ Compile-time safety β€” early validation and diagnostics
  • πŸ§ͺ Easy testing β€” plain objects, no framework coupling
  • πŸ› Superior debugging β€” short, simple call stacks

Why Convention-Based?

Traditional mediator libraries force you into rigid interface contracts like IRequestHandler<TRequest, TResponse>. This means:

  • Lots of boilerplate
  • Fixed method signatures
  • Always async (even for simple operations)
  • One handler class per message type

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 IHandler marker interface or [Handler] attributes instead. See Handler Conventions.

πŸš€ Quick Start

dotnet add package Foundatio.Mediator
// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMediator();
var app = builder.Build();
app.MapMyAppEndpoints(); // generated β€” see "Auto-Generate API Endpoints" below
app.Run();

That's it for setup. Now define messages and handlers:

// 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);
    }
}

3. Use the Mediator

// 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", "[email protected]"));
// UserCreated event automatically published to EmailHandler

// Publish events to multiple handlers
await mediator.PublishAsync(new UserCreated(user.Id, user.Email));

4. Auto-Generate API Endpoints

Skip the boilerplate of manually mapping endpoints to message handlers:

// Enable endpoint generation (in any .cs file)
[assembly: MediatorConfiguration(EndpointDiscovery = EndpointDiscovery.All)]
[HandlerCategory("Products", RoutePrefix = "products")]
public class ProductHandler
{
    public Task<Result<Product>> HandleAsync(CreateProduct command) { /* ... */ }
    public Result<Product> Handle(GetProduct query) { /* ... */ }
}

This generates:

  • POST /api/products β†’ ProductHandler.HandleAsync(CreateProduct)
  • GET /api/products/{productId} β†’ ProductHandler.Handle(GetProduct)

HTTP methods, routes, and parameter binding are inferred from message names and properties. Result<T> maps to the correct HTTP status codes automatically. Pass logEndpoints: true to see all mapped routes at startup:

app.MapProductsEndpoints(logEndpoints: true);

See Endpoints Guide for route customization, OpenAPI metadata, authorization, and more.

πŸ“š Learn More

πŸ‘‰ Complete Documentation

Key topics:

πŸ“‚ Sample Applications

Explore complete working examples:

  • Console Sample - Simple command-line application demonstrating handlers, middleware, and cascading messages
  • Clean Architecture Sample - Modular monolith showcasing:
    • Clean Architecture layers with domain separation
    • Repository pattern for data access
    • Cross-module communication via mediator
    • Domain events for loose coupling
    • Auto-generated API endpoints
    • Shared middleware across modules

πŸ” Viewing Generated Code

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.

πŸ“¦ CI Packages (Feedz)

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

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

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. See our documentation for development guidelines.

πŸ”— Related Projects

@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
  • Immediate.Handlers - another implementation of the mediator pattern in .NET using source-generation.

πŸ“„ License

Apache-2.0 License

Changes from Previous Version

No structural changes between v1.0.0-rc.11 and v1.0.0-rc.12.

Adoption Assessment

A verified publisher signal is available. Assess fit from the package's supported frameworks, license and dependency graph rather than popularity alone.

This version is marked prerelease. Validate its API and upgrade path before production use.Compatibility metadata lists 1 target framework; confirm the exact target used by your application.

Related Guides & Workflows

Learn how to evaluate, integrate, or audit this package in your .NET project.