Foundatio.Mediator.Abstractions 1.0.0-rc.10

Prefix Reserved
This is a prerelease version of Foundatio.Mediator.Abstractions.
There is a newer version of this package available.
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
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Foundatio.Mediator.Abstractions" Version="1.0.0-rc.10" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Foundatio.Mediator.Abstractions" Version="1.0.0-rc.10" />
                    
Directory.Packages.props
<PackageReference Include="Foundatio.Mediator.Abstractions" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Foundatio.Mediator.Abstractions --version 1.0.0-rc.10
                    
#r "nuget: Foundatio.Mediator.Abstractions, 1.0.0-rc.10"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Foundatio.Mediator.Abstractions@1.0.0-rc.10
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Foundatio.Mediator.Abstractions&version=1.0.0-rc.10&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Foundatio.Mediator.Abstractions&version=1.0.0-rc.10&prerelease
                    
Install as a Cake Tool

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 (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 IHandler marker 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 β†’ CreateProduct handler
  • GET /api/products/{productId} β†’ GetProduct handler
  • 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

πŸ‘‰ 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>
    
    <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.

@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 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

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
Loading failed