{"id":13727566,"url":"https://github.com/ImmediatePlatform/Immediate.Handlers","last_synced_at":"2025-05-07T23:31:41.429Z","repository":{"id":215640220,"uuid":"739161896","full_name":"ImmediatePlatform/Immediate.Handlers","owner":"ImmediatePlatform","description":"Source Generated implementation of the Mediator pattern","archived":false,"fork":false,"pushed_at":"2024-11-13T19:04:03.000Z","size":267,"stargazers_count":65,"open_issues_count":4,"forks_count":2,"subscribers_count":5,"default_branch":"master","last_synced_at":"2024-11-13T19:20:32.968Z","etag":null,"topics":["csharp-sourcegenerator","mediator","mediator-pattern"],"latest_commit_sha":null,"homepage":"https://immediateplatform.dev/","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/ImmediatePlatform.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"license.txt","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},"funding":{"github":["viceroypenguin"]}},"created_at":"2024-01-04T23:11:56.000Z","updated_at":"2024-11-13T19:03:16.000Z","dependencies_parsed_at":"2024-03-25T13:57:45.420Z","dependency_job_id":"aafe46ed-a6c1-4b6d-af3f-46c3ea6980fa","html_url":"https://github.com/ImmediatePlatform/Immediate.Handlers","commit_stats":null,"previous_names":["viceroypenguin/immediate.handlers","immediateplatform/immediate.handlers"],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ImmediatePlatform%2FImmediate.Handlers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ImmediatePlatform%2FImmediate.Handlers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ImmediatePlatform%2FImmediate.Handlers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ImmediatePlatform%2FImmediate.Handlers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ImmediatePlatform","download_url":"https://codeload.github.com/ImmediatePlatform/Immediate.Handlers/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224672780,"owners_count":17350806,"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-sourcegenerator","mediator","mediator-pattern"],"created_at":"2024-08-03T02:00:23.335Z","updated_at":"2024-11-14T18:31:13.417Z","avatar_url":"https://github.com/ImmediatePlatform.png","language":"C#","readme":"# Immediate.Handlers\n\n[![NuGet](https://img.shields.io/nuget/v/Immediate.Handlers.svg?style=plastic)](https://www.nuget.org/packages/Immediate.Handlers/)\n[![GitHub release](https://img.shields.io/github/release/ImmediatePlatform/Immediate.Handlers.svg)](https://GitHub.com/ImmediatePlatform/Immediate.Handlers/releases/)\n[![GitHub license](https://img.shields.io/github/license/ImmediatePlatform/Immediate.Handlers.svg)](https://github.com/ImmediatePlatform/Immediate.Handlers/blob/master/license.txt) \n[![GitHub issues](https://img.shields.io/github/issues/ImmediatePlatform/Immediate.Handlers.svg)](https://GitHub.com/ImmediatePlatform/Immediate.Handlers/issues/) \n[![GitHub issues-closed](https://img.shields.io/github/issues-closed/ImmediatePlatform/Immediate.Handlers.svg)](https://GitHub.com/ImmediatePlatform/Immediate.Handlers/issues?q=is%3Aissue+is%3Aclosed) \n[![GitHub Actions](https://github.com/ImmediatePlatform/Immediate.Handlers/actions/workflows/build.yml/badge.svg)](https://github.com/ImmediatePlatform/Immediate.Handlers/actions)\n---\n\nImmediate.Handlers is an implementation of the mediator pattern in .NET using source-generation. All pipeline behaviors\nare determined and the call-tree built at compile-time; meaning that all dependencies are enforced via compile-time\nsafety checks. Behaviors and dependencies are obtained via DI at runtime based on compile-time determined dependencies.\n\n#### Examples\n* Minimal Api: [Normal](./samples/Normal)\n\n## Installing Immediate.Handlers\n\nYou can install [Immediate.Handlers with NuGet](https://www.nuget.org/packages/Immediate.Handlers):\n\n    Install-Package Immediate.Handlers\n    \nOr via the .NET Core command line interface:\n\n    dotnet add package Immediate.Handlers\n\nEither commands, from Package Manager Console or .NET Core CLI, will download and install Immediate.Handlers.\n\n## Using Immediate.Handlers\n### Creating Handlers\n\nCreate a Handler by adding the following code:\n\n```cs\n[Handler]\npublic static partial class GetUsersQuery\n{\n    public record Query;\n\n    private static ValueTask\u003cIEnumerable\u003cUser\u003e\u003e HandleAsync(\n        Query _,\n        UsersService usersService,\n        CancellationToken token\n\t)\n    {\n        return usersService.GetUsers();\n    }\n}\n```\n\nThis will automatically create a new class, `GetUsersQuery.Handler`, which encapsulates the following:\n* attaching any behaviors defined for all queries in the assembly\n* using a class to receive any DI services, such as `UsersService`\n\nAny consumer can now do the following:\n```cs\npublic class Consumer(GetUsersQuery.Handler handler)\n{\n\tpublic async Task Consumer(CancellationToken token)\n\t{\n\t\tvar response = await handler.HandleAsync(new(), token);\n\t\t// do something with response\n\t}\n}\n```\n\nFor Command handlers, use a `ValueTask`, and Immediate.Handlers will insert a return type\nof `ValueTuple` to your handler automatically. \n```cs\n[Handler]\npublic static partial class CreateUserCommand\n{\n    public record Command(string Email);\n\n    private static async ValueTask HandleAsync( \n        Command command,\n        UsersService usersService,\n        CancellationToken token\n\t)\n    {\n        await usersService.CreateUser(command.Email);\n    }\n}\n```\n\nIn case your project layout does not allow direct for references between consumer and handler, the handler will also be\nregistered as an `IHandler\u003cTRequest, Response\u003e`.\n\n```cs\npublic class Consumer(IHandler\u003cQuery, IEnumerable\u003cUser\u003e\u003e handler)\n{\n\tpublic async Task Consumer(CancellationToken token)\n\t{\n\t\tvar response = await handler.HandleAsync(new(), token);\n\t\t// do something with response\n\t}\n}\n```\n\n### Creating Behaviors\n\nCreate a behavior by implementing the `Immediate.Handlers.Shared.Behaviors\u003c,\u003e` class, as so:\n```cs\npublic sealed class LoggingBehavior\u003cTRequest, TResponse\u003e(ILogger\u003cLoggingBehavior\u003cTRequest, TResponse\u003e\u003e logger)\n\t: Behavior\u003cTRequest, TResponse\u003e\n{\n\tpublic override async ValueTask\u003cTResponse\u003e HandleAsync(TRequest request, CancellationToken cancellationToken)\n\t{\n\t\tlogger.LogInformation(\"LoggingBehavior.Enter\");\n\t\tvar response = await Next(request, cancellationToken);\n\t\tlogger.LogInformation(\"LoggingBehavior.Exit\");\n\t\treturn response;\n\t}\n}\n```\n\nThis can be registered assembly-wide using:\n```cs\n[assembly: Behaviors(\n\ttypeof(LoggingBehavior\u003c,\u003e)\n)]\n```\n\nor on an individual handler using:\n```cs\n[Handler]\n[Behavior(\n\ttypeof(LoggingBehavior\u003c,\u003e)\n)]\npublic static class GetUsersQuery\n{\n\t// ..\n}\n```\n\nOnce added to the pipeline, the behavior will be called as part of the pipeline to handle a request.\n\nNote: adding a `[Behavior]` attribute to a handler will disregard all assembly-wide behaviors for that handler, so any\nglobal behaviors necessary must be independently added to the handler override behaviors list.\n\n#### Behavior Constraints\n\nA constraint can be added to a behavior by using:\n```cs\npublic sealed class LoggingBehavior\u003cTRequest, TResponse\u003e\n\t: Behavior\u003cTRequest, TResponse\u003e\n\twhere TRequest : IRequestConstraint\n\twhere TResponse : IResponseConstraint\n```\n\nWhen a pipeline is generated, all potential behaviors are evaluated against the request and response types, and if\neither type does not match a given constraint, the behavior is not added to the generated pipeline.\n\n### Registering with `IServiceCollection`\n\nImmediate.Handlers supports `Microsoft.Extensions.DependencyInjection.Abstractions` directly. \n\n#### Registering Handlers\n\nIn your `Program.cs`, add a call to `services.AddXxxHandlers()`, where `Xxx` is the shortened form of the project name.\n* For a project named `Web`, it will be `services.AddWebHandlers()`\n* For a project named `Application.Web`, it will be `services.AddApplicationWebHandlers()`\n\nThis registers all classes in the assembly marked with `[Handler]`.\n\n#### Registering Behaviors\n\nIn your `Program.cs`, add a call to `services.AddXxxBehaviors()`, where `Xxx` is the shortened form of the project name.\n* For a project named `Web`, it will be `services.AddWebBehaviors()`\n* For a project named `Application.Web`, it will be `services.AddApplicationWebBehaviors()`\n\nThis registers all behaviors referenced in any `[Behaviors]` attribute.\n\n### Using with Swashbuckle\nFor Swagger to work the JSON schema generated is required to have unique schemaId's. To achieve this, Swashbuckle uses class names as simple schemaId's.\nWhen using Immediate Handlers classes with a controller action inside, you might end up with Swashbuckle stating an error similar to this:\n\n```\nSwashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Failed to generate schema for type - MyApp.Api.DeleteUser+Command. See inner exception\nSystem.InvalidOperationException: Can't use schemaId \"$Command\" for type \"$MyApp.Api.DeleteUser+Command\". The same schemaId is already used for type \"$MyApp.Api.CreateUserCommand+Command\"\n```\n\nThis error indicates Swashbuckle is trying to use two classes named `Command` from two (or more) different Handlers in different namespaces.\n\nTo fix this, you have to define the following options in your SwaggerGen configuration:\n\n```cs\nbuilder.Services.AddSwaggerGen( options =\u003e\n{\n    options.CustomSchemaIds(x =\u003e x.FullName?.Replace(\"+\", \".\", StringComparison.Ordinal));\n});\n```\n\n## Performance Comparisons\n\nAll performance benchmarks reported use the following environment:\n```\n// * Summary *\n\nBenchmarkDotNet v0.14.0, Windows 11 (10.0.22631.4317/23H2/2023Update/SunValley3)\n12th Gen Intel Core i7-12700H, 1 CPU, 20 logical and 14 physical cores\n.NET SDK 9.0.100\n  [Host]     : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2\n  DefaultJob : .NET 9.0.0 (9.0.24.52809), X64 RyuJIT AVX2\n```\n\n#### [Benchmarks.Simple](./benchmarks/Benchmark.Simple)\n\nThis benchmark tests the various mediator implementations with a single request/response handler.\n\n| Method                       | Mean       | Error     | Ratio | Rank | Allocated |\n|----------------------------- |-----------:|----------:|------:|-----:|----------:|\n| SendRequest_Baseline         |  0.6618 ns | 0.0127 ns |  1.00 |    1 |         - |\n| SendRequest_IHandler         | 14.0497 ns | 0.0753 ns | 21.23 |    2 |         - |\n| SendRequest_ImmediateHandler | 14.9493 ns | 0.0818 ns | 22.59 |    3 |         - |\n| SendRequest_Mediator         | 22.0218 ns | 0.0684 ns | 33.28 |    4 |         - |\n| SendRequest_IMediator        | 26.8625 ns | 0.1428 ns | 40.60 |    5 |         - |\n| SendRequest_MediatR          | 47.5135 ns | 0.4161 ns | 71.81 |    6 |     192 B |\n\n#### [Benchmarks.Large](./benchmarks/Benchmark.Large)\n\nThis benchmark tests the various mediator implementations in the face of 999 request/response handlers.\n\n| Method                       | Mean        | Error     | Ratio  | Rank | Allocated |\n|----------------------------- |------------:|----------:|-------:|-----:|----------:|\n| SendRequest_Baseline         |   0.6257 ns | 0.0202 ns |   1.00 |    1 |         - |\n| SendRequest_ImmediateHandler |  11.2358 ns | 0.0395 ns |  17.97 |    2 |         - |\n| SendRequest_IHandler         |  14.0575 ns | 0.0652 ns |  22.49 |    3 |         - |\n| SendRequest_Mediator         |  22.0874 ns | 0.0534 ns |  35.33 |    4 |         - |\n| SendRequest_MediatR          |  48.3577 ns | 0.2402 ns |  77.35 |    5 |     192 B |\n| SendRequest_IMediator        | 420.2067 ns | 4.5092 ns | 672.17 |    6 |         - |\n\n#### [Benchmarks.Behaviors](./benchmarks/Benchmark.Behaviors)\n\nThis benchmark tests a more realistic scenario of using 1 behavior and 1 service.\n\n| Method                       | Mean      | Error    | Ratio | Rank | Allocated |\n|----------------------------- |----------:|---------:|------:|-----:|----------:|\n| SendRequest_Baseline         |  47.83 ns | 0.160 ns |  1.00 |    1 |      40 B |\n| SendRequest_ImmediateHandler |  62.67 ns | 0.350 ns |  1.31 |    2 |      40 B |\n| SendRequest_IHandler         |  63.59 ns | 0.218 ns |  1.33 |    2 |      40 B |\n| SendRequest_Mediator         |  91.53 ns | 0.292 ns |  1.91 |    3 |      40 B |\n| SendRequest_IMediator        | 100.73 ns | 0.396 ns |  2.11 |    4 |      40 B |\n| SendRequest_MediatR          | 188.54 ns | 0.785 ns |  3.94 |    5 |     560 B |\n","funding_links":["https://github.com/sponsors/viceroypenguin"],"categories":["Source Generators"],"sub_categories":["Patterns"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FImmediatePlatform%2FImmediate.Handlers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FImmediatePlatform%2FImmediate.Handlers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FImmediatePlatform%2FImmediate.Handlers/lists"}