9

My command:

public class Command : IRequest { ... }

My handler:

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

My pipeline registration (not using open generics):

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

However this doesn't work: Using the generic type 'IPipelineBehavior<TRequest, TResponse>' requires 2 type arguments. And same error for MyBehavior.

The docs mention the Unit struct. How do I use it?

grokky
  • 8,537
  • 20
  • 62
  • 96

2 Answers2

9

As Mickaël Derriey pointed out, MediatR already defines IRequest, IRequestHandler and IAsyncRequestHandler to not return a value if it isn't needed.

If you look at IRequest, you can see it actually inherits from IRequest<Unit>, which means when you process Command, your pipeline behavior MyBehavior will return the Unit struct as the response by default without needing to specify an explicit response for your Command.

As an example:

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

services.AddTransient<IPipelineBehavior<Command,Unit>, MyBehavior<Command,Unit>>();
bmeredith
  • 655
  • 6
  • 8
1

I think I've figured it out, and it seems to work so far.

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

services.AddTransient<IPipelineBehavior<Command,Unit>, MyBehavior<Command,Unit>>();
grokky
  • 8,537
  • 20
  • 62
  • 96
  • 2
    MediatR defines the specific [`IRequest`](https://github.com/jbogard/MediatR/blob/master/src/MediatR/IRequest.cs#L6), [`IRequestHandler`](https://github.com/jbogard/MediatR/blob/master/src/MediatR/IRequestHandler.cs#L23) and [`IAsyncRequestHandler`](https://github.com/jbogard/MediatR/blob/master/src/MediatR/IAsyncRequestHandler.cs#L25) types for the cases where you don't want to return a value. Same behavior as specifying `Unit` as a return type, the semantics are closer to what you try to achieve since you don't need to return a `Unit` instance in the handler. – Mickaël Derriey Feb 22 '17 at 21:14