{"id":13570139,"url":"https://github.com/martinothamar/Mediator","last_synced_at":"2025-04-04T06:31:51.238Z","repository":{"id":37555365,"uuid":"353349406","full_name":"martinothamar/Mediator","owner":"martinothamar","description":"A high performance implementation of Mediator pattern in .NET using source generators.","archived":false,"fork":false,"pushed_at":"2024-06-23T08:02:12.000Z","size":921,"stargazers_count":2324,"open_issues_count":40,"forks_count":83,"subscribers_count":41,"default_branch":"main","last_synced_at":"2025-04-03T22:05:50.666Z","etag":null,"topics":["csharp","csharp-sourcegenerator","dotnet","dotnet-core","dotnet-standard","dotnetcore","mediator","mediator-pattern","source-gen","source-generation","source-generators","sourcegenerator"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/martinothamar.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-31T12:30:30.000Z","updated_at":"2025-04-03T20:54:53.000Z","dependencies_parsed_at":"2024-01-06T02:09:59.973Z","dependency_job_id":"a493592a-7091-4660-84de-9684c3f1bdb5","html_url":"https://github.com/martinothamar/Mediator","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/martinothamar%2FMediator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/martinothamar%2FMediator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/martinothamar%2FMediator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/martinothamar%2FMediator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/martinothamar","download_url":"https://codeload.github.com/martinothamar/Mediator/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247134586,"owners_count":20889401,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["csharp","csharp-sourcegenerator","dotnet","dotnet-core","dotnet-standard","dotnetcore","mediator","mediator-pattern","source-gen","source-generation","source-generators","sourcegenerator"],"created_at":"2024-08-01T14:00:48.706Z","updated_at":"2025-04-04T06:31:51.189Z","avatar_url":"https://github.com/martinothamar.png","language":"C#","funding_links":[],"categories":["C# #","C#","Mediator Pattern","Source Generators","C\\#","Content"],"sub_categories":["Patterns","32. [Mediator](https://ignatandrei.github.io/RSCG_Examples/v2/docs/Mediator) , in the [Mediator](https://ignatandrei.github.io/RSCG_Examples/v2/docs/rscg-examples#mediator) category"],"readme":"[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/martinothamar/Mediator/build.yml?branch=main)](https://github.com/martinothamar/Mediator/actions)\n[![GitHub](https://img.shields.io/github/license/martinothamar/Mediator?style=flat-square)](https://github.com/martinothamar/Mediator/blob/main/LICENSE)\n[![Downloads](https://img.shields.io/nuget/dt/mediator.abstractions?style=flat-square)](https://www.nuget.org/packages/Mediator.Abstractions/)\u003cbr/\u003e\n[![Abstractions NuGet current](https://img.shields.io/nuget/v/Mediator.Abstractions?label=Mediator.Abstractions)](https://www.nuget.org/packages/Mediator.Abstractions)\n[![SourceGenerator NuGet current](https://img.shields.io/nuget/v/Mediator.SourceGenerator?label=Mediator.SourceGenerator)](https://www.nuget.org/packages/Mediator.SourceGenerator)\n[![Abstractions NuGet prerelease](https://img.shields.io/nuget/vpre/Mediator.Abstractions?label=Mediator.Abstractions)](https://www.nuget.org/packages/Mediator.Abstractions)\n[![SourceGenerator NuGet prerelease](https://img.shields.io/nuget/vpre/Mediator.SourceGenerator?label=Mediator.SourceGenerator)](https://www.nuget.org/packages/Mediator.SourceGenerator)\u003cbr/\u003e\n\n# Mediator\n\n\u003e **Note**\n\u003e\n\u003e **Version 3.0** is currently being developed. See status and provide feedback [here (#98)](https://github.com/martinothamar/Mediator/issues/98)\n\nThis is a high performance .NET implementation of the Mediator pattern using the [source generators](https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/) feature introduced in .NET 5.\nThe API and usage is mostly based on the great [MediatR](https://github.com/jbogard/MediatR) library, with some deviations to allow for better performance.\nPackages are .NET Standard 2.1 compatible.\n\nThe mediator pattern is great for implementing cross cutting concern (logging, metrics, etc) and avoiding \"fat\" constructors due to lots of injected services.\n\nGoals for this library\n* High performance\n  * Runtime performance can be the same for both runtime reflection and source generator based approaches, but it's easier to optimize in the latter case\n* AOT friendly\n  * MS are investing time in various AOT scenarios, and for example iOS requires AOT compilation\n* Build time errors instead of runtime errors\n  * The generator includes diagnostics, i.e. if a handler is not defined for a request, a warning is emitted\n\nIn particular, source generators in this library is used to\n* Generate code for DI registration\n* Generate code for `IMediator` implementation\n  * Request/Command/Query `Send` methods are monomorphized (1 method per T), the generic `ISender.Send` methods rely on these\n  * You can use both `IMediator` and `Mediator`, the latter allows for better performance\n* Generate diagnostics related messages and message handlers\n\nSee this great video by [@Elfocrash / Nick Chapsas](https://github.com/Elfocrash), covering both similarities and differences between Mediator and MediatR\n\n[![Using MediatR in .NET? Maybe replace it with this](https://img.youtube.com/vi/aaFLtcf8cO4/0.jpg)](https://www.youtube.com/watch?v=aaFLtcf8cO4)\n\n## Table of Contents\n\n- [Mediator](#mediator)\n  - [Table of Contents](#table-of-contents)\n  - [2. Benchmarks](#2-benchmarks)\n  - [3. Usage and abstractions](#3-usage-and-abstractions)\n    - [3.1. Message types](#31-message-types)\n    - [3.2. Handler types](#32-handler-types)\n    - [3.3. Pipeline types](#33-pipeline-types)\n      - [3.3.1. Message validation example](#331-message-validation-example)\n      - [3.3.2. Error logging example](#332-error-logging-example)\n    - [3.4. Configuration](#34-configuration)\n  - [4. Getting started](#4-getting-started)\n    - [4.1. Add package](#41-add-package)\n    - [4.2. Add Mediator to DI container](#42-add-mediator-to-di-container)\n    - [4.3. Create `IRequest\u003c\u003e` type](#43-create-irequest-type)\n    - [4.4. Use pipeline behaviors](#44-use-pipeline-behaviors)\n    - [4.5. Constrain `IPipelineBehavior\u003c,\u003e` message with open generics](#45-constrain-ipipelinebehavior-message-with-open-generics)\n    - [4.6. Use notifications](#46-use-notifications)\n    - [4.7. Polymorphic dispatch with notification handlers](#47-polymorphic-dispatch-with-notification-handlers)\n    - [4.8. Notification handlers also support open generics](#48-notification-handlers-also-support-open-generics)\n    - [4.9. Notification publishers](#49-notification-publishers)\n    - [4.10. Use streaming messages](#410-use-streaming-messages)\n  - [5. Diagnostics](#5-diagnostics)\n  - [6. Differences from MediatR](#6-differences-from-mediatr)\n  - [7. Versioning](#7-versioning)\n\n## 2. Benchmarks\n\nThis benchmark exposes the perf overhead of the libraries.\nMediator (this library) and MediatR methods show the overhead of the respective mediator implementations.\nI've also included the [MessagePipe](https://github.com/Cysharp/MessagePipe) library as it also has great performance.\n\n* `\u003cSendRequest | Stream\u003e_Baseline`: simple method call into the handler class\n* `\u003cSendRequest | Stream\u003e_Mediator`: the concrete `Mediator` class generated by this library\n* `\u003cSendRequest | Stream\u003e_MessagePipe`: the [MessagePipe](https://github.com/Cysharp/MessagePipe) library\n* `\u003cSendRequest | Stream\u003e_IMediator`: call through the `IMediator` interface in this library\n* `\u003cSendRequest | Stream\u003e_MediatR`: the [MediatR](https://github.com/jbogard/MediatR) library\n\nSee [benchmarks code](/benchmarks/Mediator.Benchmarks/Request) for more details on the measurement.\n\n\u003e **Warning**\n\u003e\n\u003e A current limitation of this library is that performance degrades significantly for projects with a large number of messages (\u003e500)\n\u003e There is ongoing work on resolving this for version 3.0 ([#48](https://github.com/martinothamar/Mediator/issues/48)).\n\n![Requests benchmark](/img/request_benchmark.png \"Requests benchmark\")\n\n![Stream benchmark](/img/stream_benchmark.png \"Stream benchmark\")\n\n## 3. Usage and abstractions\n\nThere are two NuGet packages needed to use this library\n* Mediator.SourceGenerator\n  * To generate the `IMediator` implementation and dependency injection setup.\n* Mediator.Abstractions\n  * Message types (`IRequest\u003c,\u003e`, `INotification`), handler types (`IRequestHandler\u003c,\u003e`, `INotificationHandler\u003c\u003e`), pipeline types (`IPipelineBehavior`)\n\nYou install the source generator package into your edge/outermost project (i.e. ASP.NET Core application, Background worker project),\nand then use the `Mediator.Abstractions` package wherever you define message types and handlers.\nStandard message handlers are automatically picked up and added to the DI container in the generated `AddMediator` method.\n*Pipeline behaviors need to be added manually (including pre/post/exception behaviors).*\n\nFor example implementations, see the [/samples](/samples) folder.\nSee the [ASP.NET Core clean architecture sample](/samples/ASPNET_Core_CleanArchitecture) for a more real world setup.\n\n### 3.1. Message types\n\n* `IMessage` - marker interface\n* `IStreamMessage` - marker interface\n* `IBaseRequest` - marker interface for requests\n* `IRequest` - a request message, no return value (`ValueTask\u003cUnit\u003e`)\n* `IRequest\u003cout TResponse\u003e` - a request message with a response (`ValueTask\u003cTResponse\u003e`)\n* `IStreamRequest\u003cout TResponse\u003e` - a request message with a streaming response (`IAsyncEnumerable\u003cTResponse\u003e`)\n* `IBaseCommand` - marker interface for commands\n* `ICommand` - a command message, no return value (`ValueTask\u003cUnit\u003e`)\n* `ICommand\u003cout TResponse\u003e` - a command message with a response (`ValueTask\u003cTResponse\u003e`)\n* `IStreamCommand\u003cout TResponse\u003e` - a command message with a streaming response (`IAsyncEnumerable\u003cTResponse\u003e`)\n* `IBaseQuery` - marker interface for queries\n* `IQuery\u003cout TResponse\u003e` - a query message with a response (`ValueTask\u003cTResponse\u003e`)\n* `IStreamQuery\u003cout TResponse\u003e` - a query message with a streaming response (`IAsyncEnumerable\u003cTResponse\u003e`)\n* `INotification` - a notification message, no return value (`ValueTask`)\n\nAs you can see, you can achieve the exact same thing with requests, commands and queries. But I find the distinction in naming useful if you for example use the CQRS pattern or for some reason have a preference on naming in your application.\n\n### 3.2. Handler types\n\n* `IRequestHandler\u003cin TRequest\u003e`\n* `IRequestHandler\u003cin TRequest, TResponse\u003e`\n* `IStreamRequestHandler\u003cin TRequest, out TResponse\u003e`\n* `ICommandHandler\u003cin TCommand\u003e`\n* `ICommandHandler\u003cin TCommand, TResponse\u003e`\n* `IStreamCommandHandler\u003cin TCommand, out TResponse\u003e`\n* `IQueryHandler\u003cin TQuery, TResponse\u003e`\n* `IStreamQueryHandler\u003cin TQuery, out TResponse\u003e`\n* `INotificationHandler\u003cin TNotification\u003e`\n\nThese types are used in correlation with the message types above.\n\n### 3.3. Pipeline types\n\n* `IPipelineBehavior\u003cTMessage, TResponse\u003e`\n* `IStreamPipelineBehavior\u003cTMessage, TResponse\u003e`\n* `MessagePreProcessor\u003cTMessage, TResponse\u003e`\n* `MessagePostProcessor\u003cTMessage, TResponse\u003e`\n* `MessageExceptionHandler\u003cTMessage, TResponse, TException\u003e`\n\n#### 3.3.1. Message validation example\n\n```csharp\n// As a normal pipeline behavior\npublic sealed class MessageValidatorBehaviour\u003cTMessage, TResponse\u003e : IPipelineBehavior\u003cTMessage, TResponse\u003e\n    where TMessage : IValidate\n{\n    public ValueTask\u003cTResponse\u003e Handle(\n        TMessage message,\n        CancellationToken cancellationToken,\n        MessageHandlerDelegate\u003cTMessage, TResponse\u003e next\n    )\n    {\n        if (!message.IsValid(out var validationError))\n            throw new ValidationException(validationError);\n\n        return next(message, cancellationToken);\n    }\n}\n\n// Or as a pre-processor\npublic sealed class MessageValidatorBehaviour\u003cTMessage, TResponse\u003e : MessagePreProcessor\u003cTMessage, TResponse\u003e\n    where TMessage : IValidate\n{\n    protected override ValueTask Handle(TMessage message, CancellationToken cancellationToken)\n    {\n        if (!message.IsValid(out var validationError))\n            throw new ValidationException(validationError);\n\n        return default;\n    }\n}\n\n// Register as IPipelineBehavior\u003c,\u003e in either case\nservices.AddSingleton(typeof(IPipelineBehavior\u003c,\u003e), typeof(MessageValidatorBehaviour\u003c,\u003e))\n```\n\n#### 3.3.2. Error logging example\n\n```csharp\n// As a normal pipeline behavior\npublic sealed class ErrorLoggingBehaviour\u003cTMessage, TResponse\u003e : IPipelineBehavior\u003cTMessage, TResponse\u003e\n    where TMessage : IMessage\n{\n    private readonly ILogger\u003cErrorLoggingBehaviour\u003cTMessage, TResponse\u003e\u003e _logger;\n\n    public ErrorLoggingBehaviour(ILogger\u003cErrorLoggingBehaviour\u003cTMessage, TResponse\u003e\u003e logger)\n    {\n        _logger = logger;\n    }\n\n    public async ValueTask\u003cTResponse\u003e Handle(\n        TMessage message,\n        CancellationToken cancellationToken,\n        MessageHandlerDelegate\u003cTMessage, TResponse\u003e next\n    )\n    {\n        try\n        {\n            return await next(message, cancellationToken);\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, \"Error handling message of type {messageType}\", message.GetType().Name);\n            throw;\n        }\n    }\n}\n\n// Or as an exception handler\npublic sealed class ErrorLoggingBehaviour\u003cTMessage, TResponse\u003e : MessageExceptionHandler\u003cTMessage, TResponse\u003e\n    where TMessage : notnull, IMessage\n{\n    private readonly ILogger\u003cErrorLoggingBehaviour\u003cTMessage, TResponse\u003e\u003e _logger;\n\n    public ErrorLoggingBehaviour(ILogger\u003cErrorLoggingBehaviour\u003cTMessage, TResponse\u003e\u003e logger)\n    {\n        _logger = logger;\n    }\n\n    protected override ValueTask\u003cExceptionHandlingResult\u003cTResponse\u003e\u003e Handle(\n        TMessage message,\n        Exception exception,\n        CancellationToken cancellationToken\n    )\n    {\n        _logger.LogError(exception, \"Error handling message of type {messageType}\", message.GetType().Name);\n        // Let the exception bubble up by using the base class helper NotHandled:\n        return NotHandled;\n        // Or if the exception is properly handled, you can just return your own response,\n        // using the base class helper Handle().\n        // This requires you to know something about TResponse,\n        // so TResponse needs to be constrained to something,\n        // typically with a static abstract member acting as a consructor on an interface or abstract class.\n        return Handled(null!);\n    }\n}\n\n// Register as IPipelineBehavior\u003c,\u003e in either case\nservices.AddSingleton(typeof(IPipelineBehavior\u003c,\u003e), typeof(ErrorLoggingBehaviour\u003c,\u003e))\n```\n\n### 3.4. Configuration\n\nThere are two ways to configure Mediator. Configuration values are needed during compile-time since this is a source generator:\n* Assembly level attribute for configuration: `MediatorOptionsAttribute`\n* Options configuration delegate in `AddMediator` function.\n\n```csharp\nservices.AddMediator(options =\u003e\n{\n    options.Namespace = \"SimpleConsole.Mediator\";\n    options.DefaultServiceLifetime = ServiceLifetime.Transient;\n});\n\n// or\n\n[assembly: MediatorOptions(Namespace = \"SimpleConsole.Mediator\", DefaultServiceLifetime = ServiceLifetime.Transient)]\n```\n\n* `Namespace` - where the `IMediator` implementation is generated\n* `DefaultServiceLifetime` - the DI service lifetime\n  * `Singleton` - (default value) everything registered as singletons, minimal allocations\n  * `Transient` - mediator and handlers registered as transient\n  * `Scoped`    - mediator and handlers registered as scoped\n\n## 4. Getting started\n\nIn this section we will get started with Mediator and go through a sample\nillustrating the various ways the Mediator pattern can be used in an application.\n\nSee the full runnable sample code in the [Showcase sample](/samples/Showcase/).\n\n### 4.1. Add package\n\n```pwsh\ndotnet add package Mediator.SourceGenerator --version 2.0.*\ndotnet add package Mediator.Abstractions --version 2.0.*\n```\nor\n```xml\n\u003cPackageReference Include=\"Mediator.SourceGenerator\" Version=\"2.0.*\"\u003e\n  \u003cPrivateAssets\u003eall\u003c/PrivateAssets\u003e\n  \u003cIncludeAssets\u003eruntime; build; native; contentfiles; analyzers\u003c/IncludeAssets\u003e\n\u003c/PackageReference\u003e\n\u003cPackageReference Include=\"Mediator.Abstractions\" Version=\"2.0.*\" /\u003e\n```\n\n### 4.2. Add Mediator to DI container\n\nIn `ConfigureServices` or equivalent, call `AddMediator` (unless `MediatorOptions` is configured, default namespace is `Mediator`).\nThis registers your handler below.\n\n```csharp\nusing Mediator;\nusing Microsoft.Extensions.DependencyInjection;\nusing System;\n\nvar services = new ServiceCollection(); // Most likely IServiceCollection comes from IHostBuilder/Generic host abstraction in Microsoft.Extensions.Hosting\n\nservices.AddMediator();\nvar serviceProvider = services.BuildServiceProvider();\n```\n\n### 4.3. Create `IRequest\u003c\u003e` type\n\n```csharp\nvar mediator = serviceProvider.GetRequiredService\u003cIMediator\u003e();\nvar ping = new Ping(Guid.NewGuid());\nvar pong = await mediator.Send(ping);\nDebug.Assert(ping.Id == pong.Id);\n\n// ...\n\npublic sealed record Ping(Guid Id) : IRequest\u003cPong\u003e;\n\npublic sealed record Pong(Guid Id);\n\npublic sealed class PingHandler : IRequestHandler\u003cPing, Pong\u003e\n{\n    public ValueTask\u003cPong\u003e Handle(Ping request, CancellationToken cancellationToken)\n    {\n        return new ValueTask\u003cPong\u003e(new Pong(request.Id));\n    }\n}\n```\n\nAs soon as you code up message types, the source generator will add DI registrations automatically (inside `AddMediator`).\nP.S - You can inspect the code yourself - open `Mediator.g.cs` in VS from Project -\u003e Dependencies -\u003e Analyzers -\u003e Mediator.SourceGenerator -\u003e Mediator.SourceGenerator.MediatorGenerator,\nor just F12 through the code.\n\n### 4.4. Use pipeline behaviors\n\nThe pipeline behavior below validates all incoming `Ping` messages.\nPipeline behaviors currently must be added manually.\n\n```csharp\nservices.AddMediator();\nservices.AddSingleton\u003cIPipelineBehavior\u003cPing, Pong\u003e, PingValidator\u003e();\n\npublic sealed class PingValidator : IPipelineBehavior\u003cPing, Pong\u003e\n{\n    public ValueTask\u003cPong\u003e Handle(Ping request, MessageHandlerDelegate\u003cPing, Pong\u003e next, CancellationToken cancellationToken)\n    {\n        if (request is null || request.Id == default)\n            throw new ArgumentException(\"Invalid input\");\n\n        return next(request, cancellationToken);\n    }\n}\n```\n\n### 4.5. Constrain `IPipelineBehavior\u003c,\u003e` message with open generics\n\nAdd open generic handler to process all or a subset of messages passing through Mediator.\nThis handler will log any error that is thrown from message handlers (`IRequest`, `ICommand`, `IQuery`).\nIt also publishes a notification allowing notification handlers to react to errors.\nMessage pre- and post-processors along with the exception handlers can also constrain the generic type parameters in the same way.\n\n```csharp\nservices.AddMediator();\nservices.AddSingleton(typeof(IPipelineBehavior\u003c,\u003e), typeof(ErrorLoggerHandler\u003c,\u003e));\n\npublic sealed record ErrorMessage(Exception Exception) : INotification;\npublic sealed record SuccessfulMessage() : INotification;\n\npublic sealed class ErrorLoggerHandler\u003cTMessage, TResponse\u003e : IPipelineBehavior\u003cTMessage, TResponse\u003e\n    where TMessage : IMessage // Constrained to IMessage, or constrain to IBaseCommand or any custom interface you've implemented\n{\n    private readonly ILogger\u003cErrorLoggerHandler\u003cTMessage, TResponse\u003e\u003e _logger;\n    private readonly IMediator _mediator;\n\n    public ErrorLoggerHandler(ILogger\u003cErrorLoggerHandler\u003cTMessage, TResponse\u003e\u003e logger, IMediator mediator)\n    {\n        _logger = logger;\n        _mediator = mediator;\n    }\n\n    public async ValueTask\u003cTResponse\u003e Handle(TMessage message, MessageHandlerDelegate\u003cTMessage, TResponse\u003e next, CancellationToken cancellationToken)\n    {\n        try\n        {\n            var response = await next(message, cancellationToken);\n            return response;\n        }\n        catch (Exception ex)\n        {\n            _logger.LogError(ex, \"Error handling message\");\n            await _mediator.Publish(new ErrorMessage(ex));\n            throw;\n        }\n    }\n}\n```\n\n### 4.6. Use notifications\n\nWe can define a notification handler to catch errors from the above pipeline behavior.\n\n```csharp\n// Notification handlers are automatically added to DI container\n\npublic sealed class ErrorNotificationHandler : INotificationHandler\u003cErrorMessage\u003e\n{\n    public ValueTask Handle(ErrorMessage error, CancellationToken cancellationToken)\n    {\n        // Could log to application insights or something...\n        return default;\n    }\n}\n```\n\n### 4.7. Polymorphic dispatch with notification handlers\n\nWe can also define a notification handler that receives all notifications.\n\n```csharp\n\npublic sealed class StatsNotificationHandler : INotificationHandler\u003cINotification\u003e // or any other interface deriving from INotification\n{\n    private long _messageCount;\n    private long _messageErrorCount;\n\n    public (long MessageCount, long MessageErrorCount) Stats =\u003e (_messageCount, _messageErrorCount);\n\n    public ValueTask Handle(INotification notification, CancellationToken cancellationToken)\n    {\n        Interlocked.Increment(ref _messageCount);\n        if (notification is ErrorMessage)\n            Interlocked.Increment(ref _messageErrorCount);\n        return default;\n    }\n}\n```\n\n### 4.8. Notification handlers also support open generics\n\n```csharp\npublic sealed class GenericNotificationHandler\u003cTNotification\u003e : INotificationHandler\u003cTNotification\u003e\n    where TNotification : INotification // Generic notification handlers will be registered as open constrained types automatically\n{\n    public ValueTask Handle(TNotification notification, CancellationToken cancellationToken)\n    {\n        return default;\n    }\n}\n```\n\n### 4.9. Notification publishers\n\n\u003e [!IMPORTANT]  \n\u003e This API is currently in the latest 3.0 previews, not available in stable.\n\nNotification publishers are responsible for dispatching notifications to a collection of handlers.\nThere are two built in implementations:\n\n* `ForeachAwaitPublisher` - the default, dispatches the notifications to handlers in order 1-by-1\n* `TaskWhenAllPublisher` - dispatches notifications in parallel\n\nBoth of these try to be efficient by handling a number of special cases (early exit on sync completion, single-handler, array of handlers).\nBelow we implement a custom one by simply using `Task.WhenAll`.\n\n```csharp\nservices.AddMediator(options =\u003e\n{\n    options.NotificationPublisherType = typeof(FireAndForgetNotificationPublisher);\n});\n\npublic sealed class FireAndForgetNotificationPublisher : INotificationPublisher\n{\n    public async ValueTask Publish\u003cTNotification\u003e(\n        NotificationHandlers\u003cTNotification\u003e handlers,\n        TNotification notification,\n        CancellationToken cancellationToken\n    )\n        where TNotification : INotification\n    {\n        try\n        {\n            await Task.WhenAll(handlers.Select(handler =\u003e handler.Handle(notification, cancellationToken).AsTask()));\n        }\n        catch (Exception ex)\n        {\n            // Notifications should be fire-and-forget, we just need to log it!\n            // This way we don't have to worry about exceptions bubbling up when publishing notifications\n            Console.Error.WriteLine(ex);\n\n            // NOTE: not necessarily saying this is a good idea!\n        }\n    }\n}\n```\n\n\n### 4.10. Use streaming messages\n\nSince version 1.* of this library there is support for streaming using `IAsyncEnumerable`.\n\n```csharp\nvar mediator = serviceProvider.GetRequiredService\u003cIMediator\u003e();\n\nvar ping = new StreamPing(Guid.NewGuid());\n\nawait foreach (var pong in mediator.CreateStream(ping))\n{\n    Debug.Assert(ping.Id == pong.Id);\n    Console.WriteLine(\"Received pong!\"); // Should log 5 times\n}\n\n// ...\n\npublic sealed record StreamPing(Guid Id) : IStreamRequest\u003cPong\u003e;\n\npublic sealed record Pong(Guid Id);\n\npublic sealed class PingHandler : IStreamRequestHandler\u003cStreamPing, Pong\u003e\n{\n    public async IAsyncEnumerable\u003cPong\u003e Handle(StreamPing request, [EnumeratorCancellation] CancellationToken cancellationToken)\n    {\n        for (int i = 0; i \u003c 5; i++)\n        {\n            await Task.Delay(1000, cancellationToken);\n            yield return new Pong(request.Id);\n        }\n    }\n}\n```\n\n## 5. Diagnostics\n\nSince this is a source generator, diagnostics are also included. Examples below\n\n* Missing request handler\n\n![Missing request handler](/img/missing_request_handler.png \"Missing request handler\")\n\n* Multiple request handlers found\n\n![Multiple request handlers found](/img/multiple_request_handlers.png \"Multiple request handlers found\")\n\n\n## 6. Differences from [MediatR](https://github.com/jbogard/MediatR)\n\nThis is a work in progress list on the differences between this library and MediatR.\n\n* `RequestHandlerDelegate\u003cTResponse\u003e()` -\u003e `MessageHandlerDelegate\u003cTMessage, TResponse\u003e(TMessage message, CancellationToken cancellationToken)`\n  * This is to avoid excessive closure allocations. I think it's worthwhile when the cost is simply passing along the message and the cancellation token.\n* No `ServiceFactory`\n  * This library relies on the `Microsoft.Extensions.DependencyInjection`, so it only works with DI containers that integrate with those abstractions.\n* Singleton service lifetime by default\n  * MediatR in combination with `MediatR.Extensions.Microsoft.DependencyInjection` does transient service registration by default, which leads to a lot of allocations. Even if it is configured for singleton lifetime, `IMediator` and `ServiceFactory` services are registered as transient (not configurable).\n* Methods return `ValueTask\u003cT\u003e` instead of `Task\u003cT\u003e`, to allow for fewer allocations (for example if the handler completes synchronously, or using async method builder pooling/`PoolingAsyncValueTaskMethodBuilder\u003cT\u003e`)\n* This library doesn't support generic requests/notifications\n\n## 7. Versioning\n\nFor versioning this library I try to follow [semver 2.0](https://semver.org/) as best as I can, meaning\n\n* Major bump for breaking changes\n* Minor bump for new backward compatible features\n* Patch bump for bugfixes\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmartinothamar%2FMediator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmartinothamar%2FMediator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmartinothamar%2FMediator/lists"}