=============== LIBRARY RULES =============== From library maintainers: - Install with `dotnet add package AnyMediator` and register with `services.AddAnyMediator(cfg => cfg.RegisterServicesFromAssemblyContaining())`. - To migrate from MediatR, follow the 'Migrating from MediatR' guide: swap the package, the namespaces and `AddMediatR` for `AddAnyMediator`, and remove `LicenseKey`. Handler and behavior code does not change. - A request has exactly one handler: two handlers for the same request make `AddAnyMediator` throw at startup. - Pipeline behaviors are not scanned: register them with `cfg.AddOpenBehavior(typeof(MyBehavior<,>))`; the first registered is the outermost. - No license key, revenue threshold or registration is required, including for commercial use. ### Install AnyMediator package Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/getting-started.md Adds the AnyMediator NuGet package to the project. The package brings in AnyMediator.Abstractions, which holds only the interfaces. ```bash dotnet add package AnyMediator ``` -------------------------------- ### Define a request and handler Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/getting-started.md Defines a request record and its handler. The handler implements IRequestHandler and returns the user from the store. ```csharp public sealed record GetUser(int Id) : IRequest; public sealed class GetUserHandler(IUserStore store) : IRequestHandler { public Task Handle(GetUser request, CancellationToken cancellationToken) => store.FindAsync(request.Id, cancellationToken); } ``` -------------------------------- ### Use IMediator to send and publish Source: https://github.com/adiakys/anymediator/blob/main/README.md Inject IMediator to combine sending commands and publishing notifications. The example shows sending a CreateOrder command and publishing an OrderPlaced notification. ```csharp public class OrderService(IMediator mediator) { public async Task PlaceOrder(Order order) { var result = await mediator.Send(new CreateOrder(order)); await mediator.Publish(new OrderPlaced(result.Id)); } } ``` -------------------------------- ### Send a request with ISender Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/getting-started.md Injects ISender into a minimal API endpoint and sends a GetUser request. The sender dispatches the request to the registered handler. ```csharp app.MapGet("/users/{id}", (int id, ISender sender, CancellationToken ct) => sender.Send(new GetUser(id), ct)); ``` -------------------------------- ### Register AnyMediator with AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/getting-started.md Registers AnyMediator on the IServiceCollection and scans the assembly containing Program for handlers. Pipeline behaviors are not scanned; add them with AddOpenBehavior. ```csharp using AnyMediator; var builder = WebApplication.CreateBuilder(args); builder.Services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); }); ``` -------------------------------- ### Dispatch request via ISender Source: https://github.com/adiakys/anymediator/blob/main/README.md Inject ISender into a controller and call Send with the request to get the response. If no handler is registered, Send throws. ```csharp public class UserController(ISender sender) { public async Task Get(int id) { return await sender.Send(new GetUser(id)); } } ``` -------------------------------- ### Dispatch stream request via ISender Source: https://github.com/adiakys/anymediator/blob/main/README.md Inject ISender (or IMediator) and call CreateStream to get an IAsyncEnumerable of results. The stream pipeline behaviors are independent from regular IPipelineBehavior. ```csharp public class LogsController(ISender sender) { public async IAsyncEnumerable Tail(string source, [EnumeratorCancellation] CancellationToken ct) { await foreach (var line in sender.CreateStream(new StreamLogs(source), ct)) yield return line; } } ``` -------------------------------- ### Registering behaviors with AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/pipeline-behaviors.md Behaviors are not auto-discovered; register them explicitly. AddOpenBehavior registers an open generic behavior for every request. The example registers LoggingBehavior and ValidationBehavior. ```csharp services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); cfg.AddOpenBehavior(typeof(ValidationBehavior<,>)); }); ``` -------------------------------- ### Set TypeEvaluator to exclude types in .Testing namespace Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/configuration.md Use this to leave a type out of scanning, for example a handler that only tests use. The predicate returns true for types whose namespace does not end with '.Testing'. ```csharp cfg.TypeEvaluator = type => type.Namespace?.EndsWith(".Testing") != true; ``` -------------------------------- ### Run AnyMediator performance benchmarks Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/performance.md Run the BenchmarkDotNet suite for AnyMediator performance tests on .NET 10. Use the --filter '*' option to run all benchmarks. ```bash dotnet run -c Release --project tests/AnyMediator.PerformanceTests -- --filter '*' ``` -------------------------------- ### Implement IRequestPreProcessor and IRequestPostProcessor Source: https://github.com/adiakys/anymediator/blob/main/README.md Define pre- and post-processor classes for a request type. Pre-processors run before the handler; post-processors run after the handler returns successfully and are skipped if the handler or any preceding step throws. Multiple processors per request type are supported and execute in registration order. ```csharp public sealed class ValidateUser : IRequestPreProcessor { public Task Process(GetUser request, CancellationToken cancellationToken) { if (request.Id <= 0) throw new ArgumentException("Invalid user id."); return Task.CompletedTask; } } public sealed class AuditUserAccess : IRequestPostProcessor { public Task Process(GetUser request, User response, CancellationToken cancellationToken) { // record the access return Task.CompletedTask; } } ``` -------------------------------- ### Subscribe to OpenTelemetry tracing and metrics Source: https://github.com/adiakys/anymediator/blob/main/README.md Enable OpenTelemetry tracing and metrics for AnyMediator by adding the ActivitySource and Meter. Nothing is recorded until you subscribe. ```csharp builder.Services.AddOpenTelemetry() .WithTracing(t => t.AddSource(AnyMediatorDiagnostics.ActivitySourceName)) .WithMetrics(m => m.AddMeter(AnyMediatorDiagnostics.MeterName)); ``` -------------------------------- ### Add package: dotnet add package AnyMediator.Abstractions Source: https://github.com/adiakys/anymediator/blob/main/README.md Command to add the AnyMediator.Abstractions package during upgrade from OpenMediatR. ```bash dotnet add package AnyMediator.Abstractions ``` -------------------------------- ### Set up OpenTelemetry tracing and metrics for AnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/tracing.md Registers OpenTelemetry with the AnyMediator ActivitySource and Meter, plus ASP.NET Core instrumentation and OTLP exporters. No extra package or configuration is needed; nothing is recorded until a listener subscribes. ```csharp using AnyMediator; builder.Services.AddOpenTelemetry() .WithTracing(tracing => tracing .AddSource(AnyMediatorDiagnostics.ActivitySourceName) .AddAspNetCoreInstrumentation() .AddOtlpExporter()) .WithMetrics(metrics => metrics .AddMeter(AnyMediatorDiagnostics.MeterName) .AddOtlpExporter()); ``` -------------------------------- ### Replace OpenMediatRConfiguration with AnyMediatorConfiguration Source: https://github.com/adiakys/anymediator/blob/main/README.md Replace the configuration class name during upgrade. ```csharp AnyMediatorConfiguration ``` -------------------------------- ### Swap MediatR package for AnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/migrating-from-mediatr.md Run these dotnet CLI commands to remove the MediatR package and add AnyMediator. If the project referenced MediatR.Contracts, reference AnyMediator.Abstractions instead. ```bash dotnet remove package MediatR dotnet add package AnyMediator ``` -------------------------------- ### Replace package: dotnet remove package OpenMediatR.Abstractions Source: https://github.com/adiakys/anymediator/blob/main/README.md Command to remove the OpenMediatR.Abstractions package when upgrading to AnyMediator.Abstractions. ```bash dotnet remove package OpenMediatR.Abstractions ``` -------------------------------- ### Define request and handler for IRequest Source: https://github.com/adiakys/anymediator/blob/main/README.md Create a request record implementing IRequest and a handler implementing IRequestHandler. Each request type must have exactly one handler; otherwise AddAnyMediator throws and names both classes. ```csharp public sealed record GetUser(int Id) : IRequest; public sealed class GetUserHandler : IRequestHandler { public Task Handle(GetUser request, CancellationToken cancellationToken) { // resolve and return the user } } ``` -------------------------------- ### Define command and handler for IRequest (no return) Source: https://github.com/adiakys/anymediator/blob/main/README.md For commands that return no value, use IRequest without a type parameter and implement IRequestHandler. The Handle method returns Task.CompletedTask. ```csharp public sealed record DeleteUser(int Id) : IRequest; public sealed class DeleteUserHandler : IRequestHandler { public Task Handle(DeleteUser request, CancellationToken cancellationToken) { // delete the user return Task.CompletedTask; } } ``` -------------------------------- ### Replace AddOpenMediatR with AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/README.md Replace the service registration method call during upgrade. ```csharp AddAnyMediator ``` -------------------------------- ### Migrate AddMediatR to AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/README.md Shows the before and after registration calls. Note that LicenseKey is removed in AnyMediator. ```csharp // Before services.AddMediatR(cfg => { cfg.LicenseKey = "..."; cfg.RegisterServicesFromAssemblyContaining(); cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); }); ``` ```csharp // After services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); }); ``` -------------------------------- ### Replace using OpenMediatR with using AnyMediator Source: https://github.com/adiakys/anymediator/blob/main/README.md Replace the using directive for the main namespace during upgrade. ```csharp using AnyMediator; ``` -------------------------------- ### Register processors with AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/README.md Register pre- and post-processors in the DI container. Option 1 explicitly adds each processor; Option 2 uses an opt-in assembly scan (mirrors MediatR). Both paths trigger auto-registration of the matching pipeline-behavior wrappers (RequestPreProcessorBehavior<,>, RequestPostProcessorBehavior<,>). Without one of them, no processor logic is wired in. ```csharp services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); // Option 1 — explicit, recommended when you want full control: cfg.AddRequestPreProcessor(); cfg.AddRequestPostProcessor(); // Option 2 — opt-in assembly scan (mirrors MediatR): // cfg.AutoRegisterRequestProcessors = true; }); ``` -------------------------------- ### Configure AddAnyMediator with assembly scanning, lifetime, behavior, and publisher Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/configuration.md Use this callback to configure AnyMediator. It registers services from the assembly containing Program, sets the lifetime to Scoped, adds an open behavior, and sets the notification publisher to TaskWhenAllPublisher. Calling AddAnyMediator more than once is safe; services and behaviors are not registered twice. ```csharp services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); cfg.Lifetime = ServiceLifetime.Scoped; cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); cfg.NotificationPublisherType = typeof(TaskWhenAllPublisher); }); ``` -------------------------------- ### Auto-register processors via assembly scan Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/processors.md Enables automatic discovery of processors by setting AutoRegisterRequestProcessors to true. ```csharp cfg.AutoRegisterRequestProcessors = true; ``` -------------------------------- ### LoggingBehavior implementing IPipelineBehavior Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/pipeline-behaviors.md Wraps request handling to log before and after the next delegate runs. Call next() to continue the pipeline; omit it to short-circuit. The TRequest constraint is narrowed to IRequest. ```csharp public sealed class LoggingBehavior(ILogger> logger) : IPipelineBehavior where TRequest : IRequest { public async Task Handle( TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { logger.LogInformation("Handling {Request}", typeof(TRequest).Name); var response = await next(); logger.LogInformation("Handled {Request}", typeof(TRequest).Name); return response; } } ``` -------------------------------- ### Change registration call from AddMediatR to AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/migrating-from-mediatr.md Replace services.AddMediatR with services.AddAnyMediator and remove the LicenseKey line. All configuration methods keep their names: RegisterServicesFromAssembly, AddOpenBehavior, AddBehavior, AddOpenStreamBehavior, AddRequestPreProcessor, AddRequestPostProcessor, AddRequestExceptionHandler, AddRequestExceptionAction, Lifetime, NotificationPublisher, NotificationPublisherType, AutoRegisterRequestProcessors, and RequestExceptionActionProcessorStrategy. ```diff - services.AddMediatR(cfg => + services.AddAnyMediator(cfg => { - cfg.LicenseKey = "..."; cfg.RegisterServicesFromAssemblyContaining(); cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); }); ``` -------------------------------- ### Replace OpenMediatR package with AnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/migrating-from-mediatr.md Run these dotnet CLI commands to remove the OpenMediatR package and add AnyMediator. This is the first step when upgrading from OpenMediatR 1.5.0 to AnyMediator 2.0.0. ```bash dotnet remove package OpenMediatR dotnet add package AnyMediator ``` -------------------------------- ### Define pre- and post-processors Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/processors.md Implements IRequestPreProcessor to validate the request and IRequestPostProcessor to audit the response. The post-processor receives the response and runs after the handler returns successfully. ```csharp public sealed class ValidateUserId : IRequestPreProcessor { public Task Process(GetUser request, CancellationToken cancellationToken) { if (request.Id <= 0) throw new ArgumentOutOfRangeException(nameof(request.Id)); return Task.CompletedTask; } } public sealed class AuditUserRead(IAuditLog audit) : IRequestPostProcessor { public Task Process(GetUser request, User response, CancellationToken cancellationToken) => audit.RecordAsync($"read user {response.Id}", cancellationToken); } ``` -------------------------------- ### Dispatch command via ISender Source: https://github.com/adiakys/anymediator/blob/main/README.md Send a command that returns no value using sender.Send. ```csharp await sender.Send(new DeleteUser(id)); ``` -------------------------------- ### Define notification and handlers (OrderPlaced, SendConfirmationEmail, UpdateInventory) Source: https://github.com/adiakys/anymediator/blob/main/README.md Defines a notification record and two handlers for it. Multiple handlers per notification type are supported; all registered handlers are executed when the notification is published. ```csharp public sealed record OrderPlaced(int OrderId) : INotification; public sealed class SendConfirmationEmail : INotificationHandler { public Task Handle(OrderPlaced notification, CancellationToken cancellationToken) { // send email return Task.CompletedTask; } } public sealed class UpdateInventory : INotificationHandler { public Task Handle(OrderPlaced notification, CancellationToken cancellationToken) { // update stock return Task.CompletedTask; } } ``` -------------------------------- ### Define LoggingBehavior pipeline behavior Source: https://github.com/adiakys/anymediator/blob/main/README.md Defines a pipeline behavior that logs before and after the next delegate. Behaviors execute in registration order: the first registered behavior is outermost, so its code before next() runs first and its code after next() runs last. ```csharp public sealed class LoggingBehavior : IPipelineBehavior where TRequest : IRequest { public async Task Handle( TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { Console.WriteLine($"Handling {typeof(TRequest).Name}"); var response = await next(); Console.WriteLine($"Handled {typeof(TRequest).Name}"); return response; } } ``` -------------------------------- ### Implement IRequestExceptionHandler and IRequestExceptionAction Source: https://github.com/adiakys/anymediator/blob/main/README.md Defines a fallback handler that recovers from ConnectionException by setting a handled response, and an action that logs failures without recovery. Both are automatically discovered by assembly scan. ```csharp public sealed class FallbackOnConnectionLost : IRequestExceptionHandler { public Task Handle( GetUser request, ConnectionException exception, RequestExceptionHandlerState state, CancellationToken cancellationToken) { state.SetHandled(User.Anonymous); // recover return Task.CompletedTask; } } public sealed class LogFailures : IRequestExceptionAction { private readonly ILogger _logger; public LogFailures(ILogger logger) => _logger = logger; public Task Execute(GetUser request, Exception exception, CancellationToken cancellationToken) { _logger.LogError(exception, "GetUser({Id}) failed", request.Id); return Task.CompletedTask; } } ``` -------------------------------- ### Forward trace context in a notification sink Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/tracing.md Adds the W3C traceparent of the current Activity to a Service Bus message so a consumer can continue the trace across services. Many broker clients already do this automatically, making the sink unnecessary. ```csharp public Task Dispatch(TNotification notification, CancellationToken cancellationToken = default) where TNotification : INotification { var message = new ServiceBusMessage(BinaryData.FromObjectAsJson(notification)) { Subject = typeof(TNotification).Name }; // W3C trace context of the publish span, read back by the consumer to continue the trace. if (Activity.Current is { } activity) message.ApplicationProperties["traceparent"] = activity.Id; return sender.SendMessageAsync(message, cancellationToken); } ``` -------------------------------- ### Replace package: dotnet remove package OpenMediatR Source: https://github.com/adiakys/anymediator/blob/main/README.md Command to remove the OpenMediatR package during upgrade to AnyMediator 2.0.0. ```bash dotnet remove package OpenMediatR ``` -------------------------------- ### Replace using OpenMediatR.NotificationPublishers with using AnyMediator.NotificationPublishers Source: https://github.com/adiakys/anymediator/blob/main/README.md Replace the using directive for the NotificationPublishers namespace during upgrade. ```csharp using AnyMediator.NotificationPublishers; ``` -------------------------------- ### Implement custom INotificationSink Source: https://github.com/adiakys/anymediator/blob/main/README.md Create a custom notification sink by implementing INotificationSink to deliver notifications through other channels like webhooks. The Dispatch method receives the notification and a cancellation token. ```csharp public sealed class WebhookNotificationSink : INotificationSink { public async Task Dispatch( TNotification notification, CancellationToken cancellationToken) where TNotification : INotification { // forward to external webhook } } ``` -------------------------------- ### Configure AnyMediator with AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/README.md Registers handlers from multiple assemblies, adds pipeline behaviors with optional lifetime overrides, sets core service lifetime (default Transient), and configures notification publishing strategy (default ForeachAwaitPublisher, sequential). ```csharp services.AddAnyMediator(cfg => { // Scan multiple assemblies cfg.RegisterServicesFromAssembly(typeof(HandlerA).Assembly); cfg.RegisterServicesFromAssembly(typeof(HandlerB).Assembly); // or: cfg.RegisterServicesFromAssemblies(assembly1, assembly2); // Add pipeline behaviors (in execution order) cfg.AddOpenBehavior(typeof(LoggingBehavior<,>)); cfg.AddOpenBehavior(typeof(ValidationBehavior<,>)); // Override behavior lifetime cfg.AddOpenBehavior(typeof(CachingBehavior<,>), ServiceLifetime.Singleton); // Set service lifetime for core services (default: Transient) cfg.Lifetime = ServiceLifetime.Scoped; // Notification publishing strategy (default: ForeachAwaitPublisher — sequential) cfg.NotificationPublisherType = typeof(TaskWhenAllPublisher); // parallel }); ``` -------------------------------- ### Define and handle a request without a response (DeleteUser) Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/requests.md Defines a request record implementing IRequest and its handler implementing IRequestHandler. The handler returns a plain Task. ```csharp public sealed record DeleteUser(int Id) : IRequest; public sealed class DeleteUserHandler(IUserStore store) : IRequestHandler { public Task Handle(DeleteUser request, CancellationToken cancellationToken) => store.DeleteAsync(request.Id, cancellationToken); } ``` -------------------------------- ### Configure notification publisher strategy with AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notifications.md Configures AnyMediator to use TaskWhenAllPublisher, which runs all handlers at once with Task.WhenAll. The default is ForeachAwaitPublisher, which runs handlers one after another and stops at the first exception. ```csharp services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); cfg.NotificationPublisherType = typeof(TaskWhenAllPublisher); }); ``` -------------------------------- ### Register processors individually Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/processors.md Registers pre- and post-processors explicitly via AddRequestPreProcessor and AddRequestPostProcessor in the AnyMediator configuration. ```csharp services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); cfg.AddRequestPreProcessor(); cfg.AddRequestPostProcessor(); }); ``` -------------------------------- ### Publish notification via IPublisher Source: https://github.com/adiakys/anymediator/blob/main/README.md Publishes an OrderPlaced notification using IPublisher. All registered handlers for the notification type are executed. ```csharp await publisher.Publish(new OrderPlaced(orderId)); ``` -------------------------------- ### Send a request with a response (GetUser) Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/requests.md Sends a GetUser request via ISender.Send. The response type is inferred from IRequest, so no type argument is needed. ```csharp User user = await sender.Send(new GetUser(42), cancellationToken); ``` -------------------------------- ### Define a stream pipeline behavior with IStreamPipelineBehavior Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/stream-requests.md Create a custom stream pipeline behavior that wraps the handler. It counts the streamed items and logs the total. The behavior must implement IStreamPipelineBehavior and use [EnumeratorCancellation] for cancellation. ```csharp public sealed class StreamLogging(ILogger> logger) : IStreamPipelineBehavior where TRequest : IStreamRequest { public async IAsyncEnumerable Handle( TRequest request, StreamHandlerDelegate next, [EnumeratorCancellation] CancellationToken cancellationToken) { var count = 0; await foreach (var item in next(cancellationToken).WithCancellation(cancellationToken)) { count++; yield return item; } logger.LogInformation("{Request} streamed {Count} items", typeof(TRequest).Name, count); } } ``` -------------------------------- ### Register custom INotificationSink in DI Source: https://github.com/adiakys/anymediator/blob/main/README.md Register the custom sink in the dependency injection container using AddSingleton. This replaces or supplements the default in-memory sink. ```csharp services.AddSingleton(); ``` -------------------------------- ### Publish a notification with runtime type using object Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notifications.md Publishes a notification whose type is only known at runtime by passing it as object. The object must implement INotification, otherwise an ArgumentException is thrown. ```csharp foreach (object domainEvent in aggregate.DequeueEvents()) await publisher.Publish(domainEvent, cancellationToken); ``` -------------------------------- ### Define notification and handlers with INotification and INotificationHandler Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notifications.md Defines an OrderPlaced notification and two handlers (SendConfirmation, ReserveStock) that run when it is published. Handlers are found by assembly scanning; a class may handle several notifications by implementing INotificationHandler more than once. ```csharp public sealed record OrderPlaced(int OrderId) : INotification; public sealed class SendConfirmation(IEmailSender email) : INotificationHandler { public Task Handle(OrderPlaced notification, CancellationToken cancellationToken) => email.SendConfirmationAsync(notification.OrderId, cancellationToken); } public sealed class ReserveStock(IInventory inventory) : INotificationHandler { public Task Handle(OrderPlaced notification, CancellationToken cancellationToken) => inventory.ReserveAsync(notification.OrderId, cancellationToken); } ``` -------------------------------- ### Send a request as object (runtime type) Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/requests.md Sends a request whose type is only known at runtime. The response comes back boxed, and is Unit.Value for a request without a response. ```csharp object? response = await sender.Send(command, cancellationToken); ``` -------------------------------- ### Define a generic handler (GetById) Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/requests.md Defines an open generic request and handler. The handler is closed for each matching request and uses AppDbContext to find an entity by ID. ```csharp public sealed record GetById(int Id) : IRequest where TEntity : class; public sealed class GetByIdHandler(AppDbContext db) : IRequestHandler, TEntity?> where TEntity : class { public async Task Handle(GetById request, CancellationToken cancellationToken) => await db.Set().FindAsync([request.Id], cancellationToken); } ``` -------------------------------- ### Open generic handler with INotificationHandler> Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notifications.md Open generic handlers are found by assembly scanning and closed for each notification they match, constraints included. This IndexEntity handler indexes any EntityCreated notification. ```csharp public sealed record EntityCreated(TEntity Entity) : INotification; public sealed class IndexEntity(ISearchIndex index) : INotificationHandler> { public Task Handle(EntityCreated notification, CancellationToken cancellationToken) => index.AddAsync(notification.Entity, cancellationToken); } ``` -------------------------------- ### Register a stream behavior with AddOpenStreamBehavior Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/stream-requests.md Register the open stream behavior in the configuration. Stream behaviors run in registration order, with the first registered being the outermost. ```csharp cfg.AddOpenStreamBehavior(typeof(StreamLogging<,>)); ``` -------------------------------- ### Change namespace from MediatR to AnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/migrating-from-mediatr.md Replace all MediatR usings with AnyMediator. The only exception is notification publishers (TaskWhenAllPublisher, ForeachAwaitPublisher) which remain in AnyMediator.NotificationPublishers. Global usings work the same way. ```diff - using MediatR; - using MediatR.Pipeline; + using AnyMediator; - using MediatR.NotificationPublishers; + using AnyMediator.NotificationPublishers; ``` -------------------------------- ### Pipeline wrapper order with processors and exception handlers Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/pipeline-behaviors.md AnyMediator adds its own wrappers around user behaviors when processors or exception handlers are used. Exception actions/handlers are outermost; post-processors then pre-processors are innermost next to the handler. ```text exception actions and exception handlers outermost your behaviors, in registration order post-processors, then pre-processors innermost, next to the handler ``` -------------------------------- ### Execution order of registered behaviors Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/pipeline-behaviors.md Behaviors run in registration order; the first registered is outermost. This shows the order for LoggingBehavior and ValidationBehavior around the handler. ```text LoggingBehavior before next() ValidationBehavior before next() handler ValidationBehavior after next() LoggingBehavior after next() ``` -------------------------------- ### Implement INotificationSink for Service Bus Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notification-sinks.md Defines a custom sink that sends notifications to Azure Service Bus. The Dispatch method creates a ServiceBusMessage from the notification and sends it asynchronously. Register this sink with AddSingleton() to deliver notifications beyond in-process handlers. ```csharp public sealed class ServiceBusSink(ServiceBusSender sender) : INotificationSink { public Task Dispatch(TNotification notification, CancellationToken cancellationToken = default) where TNotification : INotification { var message = new ServiceBusMessage(BinaryData.FromObjectAsJson(notification)) { Subject = typeof(TNotification).Name, }; return sender.SendMessageAsync(message, cancellationToken); } } ``` -------------------------------- ### Register exception handler and action explicitly Source: https://github.com/adiakys/anymediator/blob/main/README.md Registers the handler and action via AddAnyMediator configuration when automatic assembly scan is not used. Requires AddRequestExceptionHandler and AddRequestExceptionAction. ```csharp services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); cfg.AddRequestExceptionHandler(); cfg.AddRequestExceptionAction(); }); ``` -------------------------------- ### Define a stream request and handler with IStreamRequest and IStreamRequestHandler Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/stream-requests.md Define a stream request that returns results as IAsyncEnumerable. The handler implements IStreamRequestHandler and yields each item from the source. Use [EnumeratorCancellation] to propagate cancellation. ```csharp public sealed record TailLog(string Source) : IStreamRequest; public sealed class TailLogHandler(ILogReader reader) : IStreamRequestHandler { public async IAsyncEnumerable Handle( TailLog request, [EnumeratorCancellation] CancellationToken cancellationToken) { await foreach (var line in reader.ReadAsync(request.Source, cancellationToken)) yield return line; } } ``` -------------------------------- ### Filter notifications with IIntegrationEvent Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notification-sinks.md Defines an interface to mark notifications for forwarding and shows a Dispatch method that only sends notifications implementing IIntegrationEvent. Use this to filter which notifications a sink forwards. ```csharp public interface IIntegrationEvent : INotification; public Task Dispatch(TNotification notification, CancellationToken cancellationToken = default) where TNotification : INotification => notification is IIntegrationEvent ? Send(notification, cancellationToken) : Task.CompletedTask; ``` -------------------------------- ### Register ServiceBusSink with AddAnyMediator Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notification-sinks.md Registers the custom ServiceBusSink alongside the default sink. The AddAnyMediator call registers in-process handlers, and AddSingleton adds the sink so that every Publish also sends the message to the broker. ```csharp services.AddAnyMediator(cfg => cfg.RegisterServicesFromAssemblyContaining()); services.AddSingleton(); ``` -------------------------------- ### Send a request without a response (DeleteUser) Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/requests.md Sends a DeleteUser request via ISender.Send. Internally the response type is Unit, and pipeline behaviors see these requests as IPipelineBehavior. ```csharp await sender.Send(new DeleteUser(42), cancellationToken); ``` -------------------------------- ### Set RequestExceptionActionProcessorStrategy to ApplyForAllExceptions Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/exception-handling.md Configures RequestExceptionActionProcessorStrategy to ApplyForAllExceptions so actions run for every exception, before handlers try to recover. The default is ApplyForUnhandledExceptions, where actions run only when no handler recovered. ```csharp cfg.RequestExceptionActionProcessorStrategy = RequestExceptionActionProcessorStrategy.ApplyForAllExceptions; ``` -------------------------------- ### TransactionBehavior with narrowed constraint Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/pipeline-behaviors.md A behavior can narrow the TRequest constraint to a marker interface like ITransactional; the container applies it only to matching requests. Uses AppDbContext to begin and commit a transaction. ```csharp public interface ITransactional; public sealed class TransactionBehavior(AppDbContext db) : IPipelineBehavior where TRequest : ITransactional { public async Task Handle(TRequest request, RequestHandlerDelegate next, CancellationToken cancellationToken) { await using var transaction = await db.Database.BeginTransactionAsync(cancellationToken); var response = await next(cancellationToken); await transaction.CommitAsync(cancellationToken); return response; } } ``` -------------------------------- ### Publish a notification with IPublisher.Publish Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notifications.md Publishes an OrderPlaced notification to all its handlers. The call is awaited and can be cancelled with the provided CancellationToken. ```csharp await publisher.Publish(new OrderPlaced(orderId), cancellationToken); ``` -------------------------------- ### Act without recovering using IRequestExceptionAction Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/exception-handling.md Implements IRequestExceptionAction to log exceptions without recovering. After every matching action runs, the original exception is re-thrown. ```csharp public sealed class LogGetUserFailure(ILogger logger) : IRequestExceptionAction { public Task Execute(GetUser request, Exception exception, CancellationToken cancellationToken) { logger.LogError(exception, "GetUser({Id}) failed", request.Id); return Task.CompletedTask; } } ``` -------------------------------- ### Consume a stream request with CreateStream Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/stream-requests.md Use ISender.CreateStream to consume the stream request. The method returns an IAsyncEnumerable that can be iterated with await foreach. The request type must implement IStreamRequest, otherwise an ArgumentException is thrown. ```csharp await foreach (var line in sender.CreateStream(new TailLog("api"), cancellationToken)) Console.WriteLine(line); ``` -------------------------------- ### Register AnyMediator in DI container Source: https://github.com/adiakys/anymediator/blob/main/README.md Call AddAnyMediator in your service configuration to scan an assembly for IRequestHandler<,> and INotificationHandler<> implementations and register them automatically. ```csharp services.AddAnyMediator(cfg => { cfg.RegisterServicesFromAssemblyContaining(); }); ``` -------------------------------- ### Recover with a fallback using IRequestExceptionHandler Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/exception-handling.md Implements IRequestExceptionHandler to return a fallback response when a TimeoutException occurs. Calling SetHandled stops the exception and the caller of Send receives the fallback; otherwise the exception propagates with its original stack trace. ```csharp public sealed class UserStoreUnavailable : IRequestExceptionHandler { public Task Handle( GetUser request, TimeoutException exception, RequestExceptionHandlerState state, CancellationToken cancellationToken) { state.SetHandled(User.Unknown(request.Id)); return Task.CompletedTask; } } ``` -------------------------------- ### Handle base types and interfaces with INotificationHandler Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/notifications.md A handler declared for a base class or interface receives every notification derived from it. This DomainEventLog handler runs for OrderPlaced and every other IDomainEvent. ```csharp public interface IDomainEvent : INotification; public sealed record OrderPlaced(int OrderId) : IDomainEvent; // Runs for OrderPlaced and for every other IDomainEvent. public sealed class DomainEventLog(ILogger logger) : INotificationHandler { public Task Handle(IDomainEvent notification, CancellationToken cancellationToken) { logger.LogInformation("{Event} published", notification.GetType().Name); return Task.CompletedTask; } } ``` -------------------------------- ### Register exception handlers and actions explicitly Source: https://github.com/adiakys/anymediator/blob/main/docs/guide/exception-handling.md Registers exception handlers and actions explicitly using AddRequestExceptionHandler and AddRequestExceptionAction. These are closed types, one per request type; open generic handlers and actions are not supported. ```csharp cfg.AddRequestExceptionHandler(); cfg.AddRequestExceptionAction(); ```