源代码生成的中介者模式实现
Immediate.Handlers is an implementation of the mediator pattern in .NET using source-generation. All pipeline behaviors are determined and the call-tree built at compile-time; meaning that all dependencies are enforced via compile-time safety checks. Behaviors and dependencies are obtained via DI at runtime based on compile-time determined dependencies.
dotnet add package Immediate.HandlersCreate a Handler by adding the following code:
[Handler]
public sealed partial class GetUsersQuery(
UsersService usersService
)
{
public record Query;
private ValueTask> HandleAsync(
Query _,
CancellationToken token
)
{
return usersService.GetUsers();
}
}This will automatically create a new class, GetUsersQuery.Handler, which encapsulates the following:
UsersServiceAny consumer can now do the following:
public class Consumer(GetUsersQuery.Handler handler)
{
public async Task Consumer(CancellationToken token)
{
var response = await handler.HandleAsync(new(), token);
// do something with response
}
}For Command handlers, use a ValueTask, and Immediate.Handlers will insert a return type
of ValueTuple to your handler automatically.
[Handler]
public sealed partial class CreateUserCommand(
UsersService usersService
)
{
public record Command(string Email);
private async ValueTask HandleAsync(
Command command,
CancellationToken token
)
{
await usersService.CreateUser(command.Email);
}
}In case your project layout does not allow direct for references between consumer and handler, the handler will also be
registered as an IHandler.
public class Consumer(IHandler> handler)
{
public async Task Consumer(CancellationToken token)
{
var response = await handler.HandleAsync(new(), token);
// do something with response
}
}Create a behavior by implementing the Immediate.Handlers.Shared.Behaviors class, as so:
public sealed class LoggingBehavior(ILogger logger)
: Behavior
{
public override async ValueTask HandleAsync(TRequest request, CancellationToken cancellationToken)
{
logger.LogInformation("LoggingBehavior.Enter");
var response = await Next(request, cancellationToken);
logger.LogInformation("LoggingBehavior.Exit");
return response;
}
}Once added to the pipeline, the behavior will be called as part of the pipeline to handle a request. They can be added to the pipeline one of three ways:
[assembly: ] attribute, as shown here:[assembly: Behaviors(
typeof(LoggingBehavior)
)][Handler]
[Behavior(
typeof(LoggingBehavior)
)]
public static class GetUsersQuery
{
// ..
}[Behaviors] attribute another attribute, as shown here:[Behaviors(
typeof(ValidationBehavior), typeof(TransactionBehavior)
)]
public sealed class DefaultBehaviorsAttribute : Attribute;
// usage
[Handler]
[DefaultBehaviors]
public sealed class GetUsersQuery
{
// ..
}Note: adding a [Behavior] attribute to a handler will disregard all assembly-wide behaviors for that handler, so any
global behaviors necessary must be independently added to the handler override behaviors list.
A constraint can be added to a behavior by using:
public sealed class LoggingBehavior
: Behavior
where TRequest : IRequestConstraint
where TResponse : IResponseConstraintWhen a pipeline is generated, all potential behaviors are evaluated against the request and response types, and if either type does not match a given constraint, the behavior is not added to the generated pipeline.
IServiceCollectionImmediate.Handlers supports Microsoft.Extensions.DependencyInjection.Abstractions directly.
In your Program.cs, add a call to services.AddXxxHandlers(), where Xxx is the application identifier.
By default, this is the short form of the assembly name. For example:
Web, it will be services.AddWebHandlers()Application.Web, it will be services.AddApplicationWebHandlers()However, this name can be overridden using [assembly: ImmediateAssemblyIdentifierAttribute("SomeIdentifier")].
Calling this AddXxxHandlers() method will register all classes in the assembly marked with [Handler].
Behavior dependencies are registered automatically alongside each handler when AddXxxHandlers() is called.
TagsAssigns string tags to the registration. When AddXxxHandlers is called with tag arguments, only registrations that share at
least one tag (or registrations with no tags) are included.
[Handler(Tags = ["worker", "background"])]
public sealed class BackgroundWorker { }Immediate.Handlers supports streaming handlers that return IAsyncEnumerable for scenarios where
responses are produced incrementally.
Create a streaming handler by returning IAsyncEnumerable from the HandleAsync method:
[Handler]
public static partial class StreamItems
{
public record Query(int Count);
private static async IAsyncEnumerable HandleAsync(
Query query,
[EnumeratorCancellation] CancellationToken token)
{
for (var i = 0; i `, allowing consumers to
use either the concrete handler or the interface abstraction:
```cs
public class Consumer(IStreamingHandler handler)
{
public async Task ConsumeAsync(CancellationToken token)
{
await foreach (var item in handler.HandleAsync(new(5), token))
Console.WriteLine(item);
}
}Create a streaming pipeline behavior by extending StreamingBehavior:
public class LoggingBehavior(ILogger logger)
: StreamingBehavior
{
public override async IAsyncEnumerable HandleAsync(
TRequest request,
[EnumeratorCancellation] CancellationToken cancellationToken)
{
logger.LogInformation("LoggingBehavior.Enter");
await foreach (var item in Next(request, cancellationToken))
yield return item;
logger.LogInformation("LoggingBehavior.Exit");
}
}
…
Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorException: Failed to generate schema for type - MyApp.Api.DeleteUser+Command. See inner exception
System.InvalidOperationException: Can't use schemaId "$Command" for type "$MyApp.Api.DeleteUser+Command". The same schemaId is already used for type "$MyApp.Api.CreateUserCommand+Command"This error indicates Swashbuckle is trying to use two classes named Command from two (or more) different Handlers in different namespaces.
To fix this, you have to define the following options in your SwaggerGen configuration:
builder.Services.AddSwaggerGen( options =>
{
options.CustomSchemaIds(x => x.FullName?.Replace("+", ".", StringComparison.Ordinal));
});For performance comparisons, check out https://github.com/ImmediatePlatform/MediatorBenchmarks.
暂无开放 Issues,或尚未同步最近议题。