Muonroi.Mediator 1.0.0-alpha.16

This is a prerelease version of Muonroi.Mediator.
dotnet add package Muonroi.Mediator --version 1.0.0-alpha.16
                    
NuGet\Install-Package Muonroi.Mediator -Version 1.0.0-alpha.16
                    
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="Muonroi.Mediator" Version="1.0.0-alpha.16" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Muonroi.Mediator" Version="1.0.0-alpha.16" />
                    
Directory.Packages.props
<PackageReference Include="Muonroi.Mediator" />
                    
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 Muonroi.Mediator --version 1.0.0-alpha.16
                    
#r "nuget: Muonroi.Mediator, 1.0.0-alpha.16"
                    
#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 Muonroi.Mediator@1.0.0-alpha.16
                    
#: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=Muonroi.Mediator&version=1.0.0-alpha.16&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Muonroi.Mediator&version=1.0.0-alpha.16&prerelease
                    
Install as a Cake Tool

Muonroi.Mediator

In-process mediator for the Muonroi ecosystem: command/query dispatching, streaming queries, fan-out notifications, and a composable pipeline of built-in and custom behaviors.

NuGet License: Apache 2.0

Muonroi.Mediator is the Muonroi Building Block's mediator implementation. It wires commands, queries, and events through a configurable pipeline of IPipelineBehavior<,> stages — covering FluentValidation, role/permission authorization, multi-tenant context checks, structured diagnostics, and exception handling — all in a single AddMMediator call. Handlers are discovered automatically by assembly scanning, keeping controllers and endpoints free of business logic.

Installation

dotnet add package Muonroi.Mediator --prerelease

Quick Start

Register the mediator and its ecosystem pipeline in Program.cs:

using Muonroi.Core.Abstractions.Context;
using Muonroi.Logging;
using Muonroi.Mediator.Mediator;
using System.Reflection;

// Structured logging
builder.Services.AddLogging(lb => lb.AddMuonroiLogging());

// Execution-context propagator (required by auth + tenant behaviors)
builder.Services.AddSingleton<ISystemExecutionContextAccessor, SystemExecutionContextAccessor>();

// Mediator with full ecosystem pipeline
builder.Services.AddMMediator(options =>
{
    options.Assemblies = [Assembly.GetExecutingAssembly()];

    // Built-in pipeline: ExceptionHandler → Diagnostics → TenantValidation
    //                   → Authorization → Validation → Pre/PostProcessor
    options.AddMuonroiEcosystem();

    // Optional: add custom outer behaviors after
    options.AddBehavior(typeof(TimingBehavior<,>));
});

// FluentValidation — validators resolve automatically via ValidationBehavior
builder.Services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly());

Define a command and its handler:

// Command (returns OrderDto)
public sealed class CreateOrderCommand : IRequest<OrderDto>
{
    public string ProductName { get; init; } = string.Empty;
    public int Quantity { get; init; }
    public decimal UnitPrice { get; init; }
}

// Handler — discovered automatically via assembly scan
public sealed class CreateOrderCommandHandler(IMediator mediator)
    : IRequestHandler<CreateOrderCommand, OrderDto>
{
    public async Task<OrderDto> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
    {
        var order = new OrderDto(Guid.NewGuid(), request.ProductName, request.Quantity,
                                 request.UnitPrice, "Pending", DateTimeOffset.UtcNow);
        // Fan-out notification to all INotificationHandler<OrderCreatedNotification>
        await mediator.Publish(new OrderCreatedNotification(order.Id, order.ProductName, order.CreatedAt),
                               cancellationToken);
        return order;
    }
}

Dispatch from a controller or minimal-API endpoint:

[HttpPost]
public async Task<IActionResult> CreateOrder(
    [FromBody] CreateOrderCommand command, CancellationToken cancellationToken)
{
    OrderDto order = await mediator.Send(command, cancellationToken);
    return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order);
}

Features

  • Command/query dispatchingIMediator.Send<TResponse>() routes to exactly one IRequestHandler<TRequest, TResponse>; unit-returning commands via IRequest (resolves to IRequest<Unit>).
  • Fan-out notificationsIMediator.Publish() dispatches to all registered INotificationHandler<TNotification> implementations.
  • Streaming queriesIMediator.CreateStream<TResponse>() returns IAsyncEnumerable<TResponse> backed by IStreamRequestHandler<TRequest, TResponse>; ASP.NET Core streams results without buffering.
  • Composable pipelineIPipelineBehavior<TRequest, TResponse> stages are registered in declared order; AddMuonroiEcosystem() registers the canonical set in one call.
  • FluentValidation integrationValidationBehavior<,> resolves all IValidator<TRequest> instances, aggregates failures, and throws MValidationException before the handler runs.
  • Role/permission authorizationMAuthorizationBehavior<,> enforces [MAuthorize(Roles = "...", Permissions = "...")] against ISystemExecutionContext.Permissions; throws MForbiddenException or MUnauthorizedException.
  • Multi-tenant context validationMTenantValidationBehavior<,> hydrates IRequestContextBag from ISystemExecutionContextAccessor and blocks tenant-protected requests (IMTenantRequest) when TenantId is absent.
  • Structured diagnosticsMDiagnosticsBehavior<,> integrates with IMTraceContext/ITraceSessionStore (no-op defaults registered automatically when AddMuonroiDiagnostics() is not called).
  • Exception handlingMExceptionHandlerBehavior<,> catches and re-routes to IRequestExceptionHandler<TRequest, TResponse, TException> implementations found in scanned assemblies.
  • Pre/post processorsIRequestPreProcessor<TRequest> and IRequestPostProcessor<TRequest, TResponse> run automatically around the handler via MPreProcessorBehavior<,> / MPostProcessorBehavior<,>.
  • Notification dispatch strategiesMNotificationStrategy.Sequential (default), ParallelWaitAll, or ParallelNoWait; per-notification override via IMStrategyNotification.
  • Base handler classMBaseCommandHandler provides injected mapper, logger, mediator, execution-context accessors, and timestamp helpers as protected members.

Configuration

MMediatorOptions

Property Type Default Description
Assemblies Assembly[] [] Assemblies scanned for handlers, processors, and exception handlers.
DefaultNotificationStrategy MNotificationStrategy Sequential Dispatch strategy for notifications that do not implement IMStrategyNotification.
builder.Services.AddMMediator(options =>
{
    options.Assemblies = [Assembly.GetExecutingAssembly()];
    options.DefaultNotificationStrategy = MNotificationStrategy.ParallelWaitAll;
    options.AddMuonroiEcosystem();           // built-in pipeline
    options.AddBehavior<TimingBehavior<,>>(); // custom outer behavior
});

Custom pipeline behavior

public sealed class TimingBehavior<TRequest, TResponse>(ILogger<TimingBehavior<TRequest, TResponse>> logger)
    : IPipelineBehavior<TRequest, TResponse>
    where TRequest : notnull
{
    public async Task<TResponse> Handle(
        TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
    {
        var sw = Stopwatch.StartNew();
        TResponse result = await next();
        logger.LogInformation("{Request} completed in {Elapsed}ms", typeof(TRequest).Name, sw.ElapsedMilliseconds);
        return result;
    }
}

Register after AddMuonroiEcosystem() to make it the outermost wrapper.

Authorization attribute

[MAuthorize(Permissions = "orders:delete")]
public sealed class DeleteOrderCommand : IRequest
{
    public Guid OrderId { get; init; }
}

MAuthorizationBehavior<,> reads ISystemExecutionContext.Permissions from ISystemExecutionContextAccessor and throws MForbiddenException when the constraint is not satisfied.

API Reference

Type Purpose
IMediator Core contract: Send, Publish, CreateStream
IRequest<TResponse> Marker for commands/queries that return a value
IRequest Marker for unit-returning commands (IRequest<Unit>)
IRequestHandler<TRequest, TResponse> Implements handling for one request type
INotification Marker for fan-out events
INotificationHandler<TNotification> Handles one notification type; multiple per notification allowed
IStreamRequest<TResponse> Marker for streaming queries
IStreamRequestHandler<TRequest, TResponse> Produces IAsyncEnumerable<TResponse>
IPipelineBehavior<TRequest, TResponse> Pipeline stage; compose via MMediatorOptions.AddBehavior()
IRequestPreProcessor<TRequest> Runs before the handler; auto-invoked by MPreProcessorBehavior<,>
IRequestPostProcessor<TRequest, TResponse> Runs after the handler; auto-invoked by MPostProcessorBehavior<,>
IRequestExceptionHandler<TRequest, TResponse, TException> Handles specific exception types thrown by a handler
IMTenantRequest<TResponse> Tag interface; enforces non-null TenantId in execution context
IMStrategyNotification Override per-notification dispatch strategy
MAuthorizeAttribute Declares role/permission requirements on a request class
MMediatorOptions Configuration object passed to AddMMediator
MBaseCommandHandler Abstract base providing mapper, logger, mediator, and context helpers
MNotificationStrategy Enum: Sequential, ParallelWaitAll, ParallelNoWait
MForbiddenException Thrown by MAuthorizationBehavior on permission failure
MUnauthorizedException Thrown when tenant or auth context is missing
Unit Void-equivalent return value for unit-returning requests

Samples

  • Quickstart.Mediator — End-to-end ASP.NET Core API demonstrating IRequest, INotification, IStreamRequest, IPipelineBehavior, pre/post processors, and [MAuthorize].

Compatibility

  • Target framework: net8.0
  • License: Apache-2.0 (OSS)

License

Apache-2.0. See LICENSE-APACHE.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on Muonroi.Mediator:

Package Downloads
Muonroi.Data.EntityFrameworkCore

Entity Framework Core infrastructure for Muonroi: MDbContext with audit, soft-delete, multi-tenant filters, and repository base.

Muonroi.Messaging.Abstractions

Message bus contracts: IIntegrationEvent, IEventHandler, and message envelope types for Muonroi messaging integrations.

Muonroi.AspNetCore

ASP.NET Core integration: auto-CRUD controllers, middleware pipeline, license protection, and Muonroi hosting extensions.

Muonroi.AspNetCore.OpenApi

OpenAPI/Swagger integration for Muonroi ASP.NET Core: schema filters, security definitions, and documentation generation.

Muonroi.Tenancy.SiteProfile.Web

ASP.NET Core middleware and SignalR hot-reload for Muonroi.Tenancy.SiteProfile.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0-alpha.16 150 6/22/2026
1.0.0-alpha.15 181 5/31/2026
1.0.0-alpha.14 172 5/15/2026
1.0.0-alpha.13 153 5/2/2026
1.0.0-alpha.12 107 4/2/2026
1.0.0-alpha.11 144 4/2/2026
1.0.0-alpha.9 85 3/30/2026
1.0.0-alpha.8 328 3/28/2026
1.0.0-alpha.7 76 3/27/2026
1.0.0-alpha.5 75 3/27/2026
1.0.0-alpha.4 76 3/27/2026
1.0.0-alpha.3 70 3/27/2026
1.0.0-alpha.2 73 3/26/2026
1.0.0-alpha.1 107 3/8/2026