Skip to main content
.NETStandard2.0

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

Published
Oct 19, 2025
1y ago
Total Downloads
22.5K
22,514

Install

dotnet add package Foundatio.Mediator.Abstractions --version 1.0.0-preview.14
ProductVersions
.NET Standard
netstandard2.0

README

FoundatioFoundatio

Build status NuGet Version feedz.io Discord

Blazingly fast, convention-based C# mediator powered by source generators and interceptors.

✨ Why Choose Foundatio Mediator?

  • πŸš€ 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* - 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

πŸš€ Complete Example

1. Install & Register

dotnet add package Foundatio.Mediator
// Program.cs
services.AddMediator();

2. Create Messages & 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();

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

πŸ“š Learn More

πŸ‘‰ Complete Documentation

Key topics:

πŸ“¦ 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

πŸ“„ License

MIT License

Changes from Previous Version

v1.0.0-previewv1.0.0-preview.14
Added Dependencies

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.