D20Tek.Mediator 0.9.5

dotnet add package D20Tek.Mediator --version 0.9.5
                    
NuGet\Install-Package D20Tek.Mediator -Version 0.9.5
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="D20Tek.Mediator" Version="0.9.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="D20Tek.Mediator" Version="0.9.5" />
                    
Directory.Packages.props
<PackageReference Include="D20Tek.Mediator" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add D20Tek.Mediator --version 0.9.5
                    
#r "nuget: D20Tek.Mediator, 0.9.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package D20Tek.Mediator@0.9.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=D20Tek.Mediator&version=0.9.5
                    
Install as a Cake Addin
#tool nuget:?package=D20Tek.Mediator&version=0.9.5
                    
Install as a Cake Tool

d20tek-mediator

Introduction

Welcome to D20Tek.Mediator. This library is a minimal implementation of the Mediator and Command pattern that can be used in any .NET project, whether it is a console application, WebApi, or Blazor application. This code is inspired by the Mediatr package. With Mediatr moving to a commercial license, I built a simplified set of use cases for my own projects as D20Tek.Mediator.

The current version of this package supports the Mediator to send commands (both sync and async) to registered CommandHandlers. Commands are routed to the appropriate handler using the ICommand and ICommandHandlerAsync (or ICommandHandler) interfaces. Along with commands, the Mediator also supports multi-cast notifications (both sync and async) to registered NotificationHandlers. Notifications are routed to all registered handlers for the same INotification and INotificationHandlerAsync (or INotificationHAndler) interfaces -- regardless of how many handlers are defined.

There are also dependency injection registration functions that will register the Mediator services and all of the command handlers in an assembly (optionally). If you wish to manually register your command handlers, that is also supported.

In the future, we may support more advanced funtionality, like command pipelines to reduce duplicative code. Is that a feature that you require in your projects? Please leave a comment, and we may add that work to our backlog sooner.

Installation

This library is a NuGet package so it is easy to add to your project. To install the package into your solution, you can use the NuGet Package Manager. In PM, please use the following command:

PM > Install-Package D20Tek.Mediator -Version 0.9.5

To install in the Visual Studio UI, go to the Tools menu > "Manage NuGet Packages". Then search for D20Tek.Mediator, and install whichever packages you require from there.

Usage

Once you've installed the NuGet package, you can start using it in your .NET projects. Within your WebApi project, you can start by registering the services with your DI container.

    builder.Services.AddMediator(typeof(Program).Assembly);

Then, you need to define your command and handler.

internal sealed record WeatherForecastCommand : ICommand<WeatherForecast[]>;

internal sealed record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

internal sealed class GetForecastCommandHandlerAsync : ICommandHandlerAsync<WeatherForecastCommand, WeatherForecast[]>
{
    private static readonly string[] _summaries =
    [
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    ];

    public Task<WeatherForecast[]> HandleAsync(WeatherForecastCommand command, CancellationToken cancellationToken) =>
        Task.FromResult(Enumerable.Range(1, 5)
                                  .Select(index =>
                                      new WeatherForecast
                                      (
                                          DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                                          Random.Shared.Next(-20, 55),
                                          _summaries[Random.Shared.Next(_summaries.Length)]
                                      )).ToArray());
}

Finally, use the command in your WebApi endpoint (this example uses MinimalApis, but it also works with Controllers).

    app.MapGet("api/v1/async/weatherforecast", async (IMediator mediator, CancellationToken cancellationToken) =>
                await mediator.SendAsync(new WeatherForecastCommand(), cancellationToken))
            .Produces<WeatherForecast[]>()
            .WithName("GetWeatherForecastAsync")
            .WithTags("Weather Service");

Note that the endpoint code gets the IMediator service from dependency injection (registered above), creates a new instance of the command, and calls SendAsync to send the message asynchronously. Mediator finds the handler that matches your command and forwards the request by calling the HandleAsync method in that CommandHandler. Everything just works correctly if you call AddMediator with the assembly that contains your commands and handlers.

Samples

For more detailed examples on how to use D20Tek.Mediator, please review the following samples:

  • MemberService - Minimal WebApi project that implements CRUD operations for a members database. It uses asynchronous endpoint definitions, commands, and command handlers to show how D20Tek.Mediator can be used for this type of service.
  • SampleApi - The simplest of Minimal WepApi projects with only variations of retrieving forecast endpoints.
  • TipCalc.Cli - This project shows how you can use D20Tek.Mediator in a console application. It creates a generic host to support dependency injection. Then uses command and handlers in a particular workflow to implement a tip calculator.

Feedback

If you use this library and have any feedback, bugs, or suggestions, please file them in the Issues section of this repository. I'm still in the process of building the library and samples, so any suggestions that would make it more useable are welcome.

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.9.5 154 7/7/2025
0.9.4 105 5/30/2025
0.9.3 245 5/13/2025
0.9.2 261 5/12/2025