Saturna.MediaThor
1.3.2
dotnet add package Saturna.MediaThor --version 1.3.2
NuGet\Install-Package Saturna.MediaThor -Version 1.3.2
<PackageReference Include="Saturna.MediaThor" Version="1.3.2" />
<PackageVersion Include="Saturna.MediaThor" Version="1.3.2" />
<PackageReference Include="Saturna.MediaThor" />
paket add Saturna.MediaThor --version 1.3.2
#r "nuget: Saturna.MediaThor, 1.3.2"
#:package Saturna.MediaThor@1.3.2
#addin nuget:?package=Saturna.MediaThor&version=1.3.2
#tool nuget:?package=Saturna.MediaThor&version=1.3.2
<p align="center"> <img src="icon.png" alt="MediaThor" width="160" /> <h1 align="center">MediaThor</h1> </p>
<p align="center"> Simplify communications between components in your C# applications.<br> <b>MediaThor</b> provides a source-generated, CQRS-friendly Mediator pattern with built-in support for dependency injection. </p>
Features
- Mediator CQRS-friendly
- Source generated request dispatcher
- Source generated request handling pipeline
- Request handling pipeline priority configuration
- Streaming response
Getting Started
Install the package via NuGet :
dotnet add package Saturna.MediaThor
Or using the Package Manager :
Install-Package Saturna.MediaThor
Usage
MediaThor works just like others. To get started start by adding the generated services to your DI container with the AddMediaThor extension method :
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services
.AddMediaThor(); // <-- here
var app = builder.Build();
Create your feature, here for the exemple we will keep it as light as possible :
public sealed record SayHelloQuery(string Name) : IRequest<string>;
public sealed class SayHelloHandler
: IRequestHandler<SayHelloQuery, string>
{
public Task<string> HandleAsync(SayHelloQuery request, CancellationToken cancellationToken)
{
return Task.FromResult($"Hello {request.Name} !");
}
}
Then create your endpoint and inject the IMediator instance :
Minimal API
app.MapGet("/hello/{name}", async (
string name,
IMediator mediator, // <-- here
CancellationToken cancellationToken) =>
{
var query = new SayHelloQuery(name);
var result = await mediator.Send(query, cancellationToken);
return Results.Ok(result);
});
Controller Based API
[ApiController]
[Route("[controller]")]
public class HelloController(IMediator mediator) // <-- here
: ControllerBase
{
// GET api/hello/{name}
[HttpGet("{name}")]
public async Task<IActionResult> SayHello(string name, CancellationToken cancellationToken)
{
var query = new SayHelloQuery(name);
var result = await mediator.Send(query, cancellationToken);
return Ok(result);
}
}
And you're done !
Going further
Handling IAsyncEnumerable<T>
In this case you should use a IStreamRequestHandler associated with a IStreamRequest. It will allow you to interact directly with an IAsyncEnumerable.
Start by creating your feature :
public sealed record RandomNumbersQuery(byte Amount) : IStreamRequest<int>;
public sealed class RandomNumbersHandler
: IStreamRequestHandler<RandomNumbersQuery, int>
{
public async IAsyncEnumerable<int> HandleAsync(RandomNumbersQuery request, [EnumeratorCancellation] CancellationToken cancellationToken)
{
for (var i = 0; i < request.Amount; i++)
{
cancellationToken.ThrowIfCancellationRequested();
yield return Random.Shared.Next(1, 1_000);
await Task.Yield();
}
}
}
Once that's done just create your endpoint :
Minimal API
app.MapGet("/enum/{amount:int}", async (
byte amount,
IMediator mediator,
CancellationToken cancellationToken) =>
{
var query = new StreamedQuery(amount);
return await mediator.CreateStream(query, cancellationToken);
});
Controller Based API
[ApiController]
[Route("[controller]")]
public class EnumController(IMediator mediator)
: ControllerBase
{
// GET api/enum/{amount}
[HttpGet("{amount:int}")]
public async IAsyncEnumerable<int> Enumerate(byte amount, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var query = new StreamedQuery(amount);
await foreach (var item in (await mediator.CreateStream(query, cancellationToken))
.WithCancellation(cancellationToken))
yield return item;
}
}
Handling request without response
You can also send request that doesn't needs any response. It could be very usefull for HTTP 204 No Response or when you want to use it as an event handler.
To be performed, your request should implements the IRequest interface and the handler should implements IRequestHandler<TRequest>.
Start by creating your feature :
public sealed record NoContentQuery : IRequest;
public sealed class NoContentHandler
: IRequestHandler<NoContentQuery>
{
public Task HandleAsync(NoContentQuery request, CancellationToken cancellationToken)
{
return Task.Delay(3_000, cancellationToken);
}
}
Create your endpoint :
Minimal API
app.MapGet("/nocontent", async (
IMediator mediator,
CancellationToken cancellationToken) =>
{
var query = new NoContentQuery();
await mediator.Send(query, cancellationToken);
return Results.NoContent();
});
Controller Based API
[ApiController]
[Route("[controller]")]
public class NoContentController(IMediator mediator)
: ControllerBase
{
// GET api/nocontent/
[HttpGet("/")]
public async Task NoContent(byte amount, CancellationToken cancellationToken)
{
var query = new NoContentQuery();
await mediator.Send(query, cancellationToken);
return NoContent();
}
}
IPipelineBehavior
Just like some others library allows you can add some pipeline behaviors.
In this exemple we will implement two dummy behaviors. All behaviors should implement the IPipelineBehavior<TRequest, TResponse> or the IPipelineBehavior<TRequest> (if the request doesn't have a result) interface.
We will start by creating a generic one, which will log in debug the received request.
public sealed class DebugLogBehavior<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
public async Task<TResponse> HandleAsync(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
{
Debug.WriteLine($"Received request : '{request}'.")
return await next(cancellationToken);
}
}
And another one more specific which will be executed only if the request is a SayHelloQuery.
public sealed class HelloSaidBehavior
: IPipelineBehavior<SayHelloQuery, string>
{
public async Task<string> HandleAsync(SayHelloQuery request, RequestHandlerDelegate<string> next, CancellationToken cancellationToken)
{
if (request.Name.Contains(' '))
throw new InvalidOperationException();
return await next(cancellationToken);
}
}
You can also define a priority order on your IPipelineBehavior just by decorating the class with the MediaThorPipePriorityAttribute.
[MediaThorPipePriority(0)] // <-- This pipeline behavior will be executed before the others.
public sealed class HelloSaidBehavior
: IPipelineBehavior<SayHelloQuery, string>
...
License
This project is licensed under the MIT License - see the LICENSE file for details.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 was computed. 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. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- Microsoft.Bcl.AsyncInterfaces (>= 10.0.2)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.