In MediatR there used to be two flavors of request types (see Request types):
IRequest<TResponse>
, for requests returning a valueIRequest
, for the ones not returning any valueDepending on which case the handler covered, it needed to implement either:
IRequestHandler<TRequest, TResponse>
, orIRequestHandler<TRequest>
So, for requests not needing any return value, the code is like:
class PingHandler : IRequestHandler<Ping>
{
internal static bool HasBeenCalled { get; set; }
public Task Handle(Ping request, CancellationToken cancellationToken)
{
// do work
return Task.CompletedTask;
}
}
Although this is still supported, since version 5 (see Migration guide 4.1.0 > 5.0.1) requests handler that return a value, and those that do not were unified into one single type IRequestHandler<T, U>
. Handler not returning a value shall return Unit
.
class Ping : IRequest<Unit> { }
class PingHandler : IRequestHandler<Ping, Unit>
{
public Task<Unit> Handle(Ping request, CancellationToken cancellationToken)
{
// do work
return Task.FromResult(Unit.Value);
}
}
C# method dispathing supports void
methods out of the box, so there is nothing special you have to do other than declaring the method as void:
class PingHandler : IPingHandler
{
void IPingHandler.Ping()
{
// do work
}
}
Or course, nothing prevents you from returning Unit
, if you prefer. It’s plain C#, after all:
interface IPingHandler
{
Unit Ping(string whatever);
}
Answer
The interface of PingHandler
does not change only because one of its methods returns void
instead of string
(e.g., there is no impact on the IoC registration).
By the way, notice that you have the freedom to return either void
or Task
, depending on the asynchronous nature of the method.