Muonroi.Mediator
1.0.0-alpha.16
dotnet add package Muonroi.Mediator --version 1.0.0-alpha.16
NuGet\Install-Package Muonroi.Mediator -Version 1.0.0-alpha.16
<PackageReference Include="Muonroi.Mediator" Version="1.0.0-alpha.16" />
<PackageVersion Include="Muonroi.Mediator" Version="1.0.0-alpha.16" />
<PackageReference Include="Muonroi.Mediator" />
paket add Muonroi.Mediator --version 1.0.0-alpha.16
#r "nuget: Muonroi.Mediator, 1.0.0-alpha.16"
#:package Muonroi.Mediator@1.0.0-alpha.16
#addin nuget:?package=Muonroi.Mediator&version=1.0.0-alpha.16&prerelease
#tool nuget:?package=Muonroi.Mediator&version=1.0.0-alpha.16&prerelease
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.
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 dispatching —
IMediator.Send<TResponse>()routes to exactly oneIRequestHandler<TRequest, TResponse>; unit-returning commands viaIRequest(resolves toIRequest<Unit>). - Fan-out notifications —
IMediator.Publish()dispatches to all registeredINotificationHandler<TNotification>implementations. - Streaming queries —
IMediator.CreateStream<TResponse>()returnsIAsyncEnumerable<TResponse>backed byIStreamRequestHandler<TRequest, TResponse>; ASP.NET Core streams results without buffering. - Composable pipeline —
IPipelineBehavior<TRequest, TResponse>stages are registered in declared order;AddMuonroiEcosystem()registers the canonical set in one call. - FluentValidation integration —
ValidationBehavior<,>resolves allIValidator<TRequest>instances, aggregates failures, and throwsMValidationExceptionbefore the handler runs. - Role/permission authorization —
MAuthorizationBehavior<,>enforces[MAuthorize(Roles = "...", Permissions = "...")]againstISystemExecutionContext.Permissions; throwsMForbiddenExceptionorMUnauthorizedException. - Multi-tenant context validation —
MTenantValidationBehavior<,>hydratesIRequestContextBagfromISystemExecutionContextAccessorand blocks tenant-protected requests (IMTenantRequest) whenTenantIdis absent. - Structured diagnostics —
MDiagnosticsBehavior<,>integrates withIMTraceContext/ITraceSessionStore(no-op defaults registered automatically whenAddMuonroiDiagnostics()is not called). - Exception handling —
MExceptionHandlerBehavior<,>catches and re-routes toIRequestExceptionHandler<TRequest, TResponse, TException>implementations found in scanned assemblies. - Pre/post processors —
IRequestPreProcessor<TRequest>andIRequestPostProcessor<TRequest, TResponse>run automatically around the handler viaMPreProcessorBehavior<,>/MPostProcessorBehavior<,>. - Notification dispatch strategies —
MNotificationStrategy.Sequential(default),ParallelWaitAll, orParallelNoWait; per-notification override viaIMStrategyNotification. - Base handler class —
MBaseCommandHandlerprovides 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)
Related Packages
Muonroi.Core— Core models, guards, and execution-context infrastructure consumed by the mediator pipeline.Muonroi.Core.Abstractions— Contracts forISystemExecutionContextAccessor,ITraceSessionStore, and exception types used by behaviors.Muonroi.Logging—IMLog<T>structured logging used byMBaseCommandHandlerandLoggingBehavior.Muonroi.Mapper—IMapperintegrated intoMBaseCommandHandler.Muonroi.Caching.Abstractions— Cache contracts available to handlers via the DI container.Muonroi.RuleEngine.Abstractions— Rule contracts consumed byMRuleEngineBehavior<,>.Muonroi.Tenancy.Abstractions— Tenancy contracts used byMTenantValidationBehavior<,>.
License
Apache-2.0. See LICENSE-APACHE.
| Product | Versions 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. |
-
net8.0
- FluentValidation (>= 12.0.0)
- Muonroi.Caching.Abstractions (>= 1.0.0-alpha.16)
- Muonroi.Core (>= 1.0.0-alpha.16)
- Muonroi.Core.Abstractions (>= 1.0.0-alpha.16)
- Muonroi.Logging (>= 1.0.0-alpha.16)
- Muonroi.Logging.Abstractions (>= 1.0.0-alpha.16)
- Muonroi.Mapper (>= 1.0.0-alpha.16)
- Muonroi.RuleEngine.Abstractions (>= 1.0.0-alpha.16)
- Muonroi.Tenancy.Abstractions (>= 1.0.0-alpha.16)
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 |