使用 void/Task 响应注册 MediatR 管道

Register a MediatR pipeline with void/Task response

我的命令:

public class Command : IRequest { ... }

我的经纪人:

public class CommandHandler : IAsyncRequestHandler<Command> { ... }

我的管道注册(不使用开放泛型):

services.AddTransient<IPipelineBehavior<Command>, MyBehavior<Command>>();

但是这不起作用:Using the generic type 'IPipelineBehavior<TRequest, TResponse>' requires 2 type arguments.MyBehavior 相同的错误。

The docs mention the Unit struct。我该如何使用它?

我想我已经弄明白了,到目前为止它似乎有效。

public class Command : IRequest<Unit> { ... }
public class CommandHandler : IAsyncRequestHandler<Command, Unit> { ... }

services.AddTransient<IPipelineBehavior<Command,Unit>, MyBehavior<Command,Unit>>();

正如 Mickaël Derriey 指出的那样,MediatR 已经将 IRequest, IRequestHandler and IAsyncRequestHandler 定义为不 return 不需要的值。

如果您查看 IRequest,您会发现它实际上继承自 IRequest<Unit>,这意味着当您处理 Command 时,您的管道行为 MyBehavior 将 return Unit 结构默认作为响应,无需为您的 Command.

指定显式响应

举个例子:

public class Command : IRequest { ... }
public class CommandHandler : IAsyncRequestHandler<Command> { ... }

services.AddTransient<IPipelineBehavior<Command,Unit>, MyBehavior<Command,Unit>>();