百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
I

Immediate.Handlers

> 编程语言
开源

源代码生成的中介者模式实现

196 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

源代码生成的中介者模式实现

Immediate.Handlers


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.

Examples

  • Minimal Api: Normal

Installing Immediate.Handlers

dotnet add package Immediate.Handlers

Using Immediate.Handlers

Creating Handlers

Create a Handler by adding the following code:

cs
[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:

  • attaching any behaviors defined for all queries in the assembly
  • using a class to receive any DI services, such as UsersService

Any consumer can now do the following:

cs
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.

cs
[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.

cs
public class Consumer(IHandler> handler)
{
	public async Task Consumer(CancellationToken token)
	{
		var response = await handler.HandleAsync(new(), token);
		// do something with response
	}
}

Creating Behaviors

Create a behavior by implementing the Immediate.Handlers.Shared.Behaviors class, as so:

cs
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;
	}
}

Using Behaviors

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:

  • Behaviors can be registered assembly-wide by using an [assembly: ] attribute, as shown here:
cs
[assembly: Behaviors(
	typeof(LoggingBehavior)
)]
  • Behaviors can be applied on an individual handler using:
cs
[Handler]
[Behavior(
	typeof(LoggingBehavior)
)]
public static class GetUsersQuery
{
	// ..
}
  • Common behavior pipelines can be defined by applying a [Behaviors] attribute another attribute, as shown here:
cs
[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.

Behavior Constraints

A constraint can be added to a behavior by using:

cs
public sealed class LoggingBehavior
	: Behavior
	where TRequest : IRequestConstraint
	where TResponse : IResponseConstraint

When 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.

Registering with IServiceCollection

Immediate.Handlers supports Microsoft.Extensions.DependencyInjection.Abstractions directly.

Registering Handlers

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:

  • For a project named Web, it will be services.AddWebHandlers()
  • For a project named 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.

Tags

Assigns 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.

csharp
[Handler(Tags = ["worker", "background"])]
public sealed class BackgroundWorker { }

Streaming Handlers

Immediate.Handlers supports streaming handlers that return IAsyncEnumerable for scenarios where responses are produced incrementally.

Streaming Handler

Create a streaming handler by returning IAsyncEnumerable from the HandleAsync method:

cs
[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);
    }
}

Streaming Behavior

Create a streaming pipeline behavior by extending StreamingBehavior:

cs
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:

cs
builder.Services.AddSwaggerGen( options =>
{
    options.CustomSchemaIds(x => x.FullName?.Replace("+", ".", StringComparison.Ordinal));
});

Performance Comparisons

For performance comparisons, check out https://github.com/ImmediatePlatform/MediatorBenchmarks.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#csharp-sourcegeneratormediatormediator-pattern

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言