Foundatio.Mediator.Abstractions
1.0.0-rc.10
Prefix Reserved
See the version list below for details.
dotnet add package Foundatio.Mediator.Abstractions --version 1.0.0-rc.10
NuGet\Install-Package Foundatio.Mediator.Abstractions -Version 1.0.0-rc.10
<PackageReference Include="Foundatio.Mediator.Abstractions" Version="1.0.0-rc.10" />
<PackageVersion Include="Foundatio.Mediator.Abstractions" Version="1.0.0-rc.10" />
<PackageReference Include="Foundatio.Mediator.Abstractions" />
paket add Foundatio.Mediator.Abstractions --version 1.0.0-rc.10
#r "nuget: Foundatio.Mediator.Abstractions, 1.0.0-rc.10"
#:package Foundatio.Mediator.Abstractions@1.0.0-rc.10
#addin nuget:?package=Foundatio.Mediator.Abstractions&version=1.0.0-rc.10&prerelease
#tool nuget:?package=Foundatio.Mediator.Abstractions&version=1.0.0-rc.10&prerelease
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 (see benchmarks)
- β‘ 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/Execute hooks with state passing
- π― Built-in Result<T> - Rich status handling without exceptions
- π Tuple returns - Automatic cascading messages
- π Auto-generated endpoints - Minimal API endpoints from handlers with zero boilerplate
- π 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
IHandlermarker interface or[Handler]attributes instead. See Handler Conventions.
π 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();
// 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", "john@example.com"));
// 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 (Optional)
Foundatio Mediator can automatically generate ASP.NET Core Minimal API endpoints from your handlers:
// Add category to group endpoints
[HandlerCategory("Products", RoutePrefix = "/api/products")]
public class ProductHandler
{
/// <summary>
/// Creates a new product in the catalog.
/// </summary>
public Task<Result<Product>> HandleAsync(CreateProduct command) { /* ... */ }
/// <summary>
/// Gets a product by ID.
/// </summary>
public Result<Product> Handle(GetProduct query) { /* ... */ }
}
// Program.cs - map the generated endpoints
app.MapProductsEndpoints();
This automatically generates:
POST /api/productsβCreateProducthandlerGET /api/products/{productId}βGetProducthandler- HTTP method inferred from message name (
Create*β POST,Get*β GET, etc.) Result<T>status mapped to HTTP status codes- OpenAPI metadata from XML doc comments
Configure with an assembly attribute:
[assembly: MediatorConfiguration(
EndpointDiscovery = EndpointDiscovery.All,
EndpointRequireAuth = true,
ProjectName = "Products"
)]
Enable XML documentation for endpoint summaries:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
See Endpoints Guide for full documentation.
π Learn More
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
- Endpoints - Auto-generated Minimal API endpoints
- Performance - Benchmarks vs other libraries
- Configuration - Assembly attribute and runtime options
π 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>
<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
MIT License
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- Microsoft.Bcl.AsyncInterfaces (>= 10.0.3)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.3)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.1)
- System.Diagnostics.DiagnosticSource (>= 10.0.3)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on Foundatio.Mediator.Abstractions:
| Package | Downloads |
|---|---|
|
Foundatio.Mediator
A fast, convention-based C# mediator library using incremental source generators |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 1.2.1 | 614 | 4/28/2026 |
| 1.2.0 | 139 | 4/28/2026 |
| 1.1.0 | 365 | 4/11/2026 |
| 1.0.1 | 612 | 3/11/2026 |
| 1.0.0 | 172 | 3/11/2026 |
| 1.0.0-rc.15 | 71 | 3/11/2026 |
| 1.0.0-rc.14 | 70 | 3/10/2026 |
| 1.0.0-rc.13 | 457 | 3/4/2026 |
| 1.0.0-rc.12 | 69 | 3/4/2026 |
| 1.0.0-rc.11 | 143 | 2/24/2026 |
| 1.0.0-rc.10 | 70 | 2/24/2026 |
| 1.0.0-rc.9 | 298 | 2/4/2026 |
| 1.0.0-rc.8 | 111 | 2/3/2026 |
| 1.0.0-rc.6 | 235 | 1/20/2026 |
| 1.0.0-rc.5 | 486 | 1/8/2026 |
| 1.0.0-rc.4 | 1,485 | 12/11/2025 |
| 1.0.0-rc.3 | 321 | 11/6/2025 |
| 1.0.0-rc.2 | 134 | 11/1/2025 |
| 1.0.0-rc.1 | 144 | 10/19/2025 |
| 1.0.0-preview.14 | 114 | 10/19/2025 |