IRequestHandler return void
Workaround solution for anyone who doesn't want to use Unit for some reason. You can create class named as VoidResult or EmptyResult then use it as return for all requests that returns nothing.
public class CreatePersonHandler : IRequestHandler<CreatePersonCommand, VoidResult>
In CreatePersonCommand
, IRequest
shouldn't have any response type specified :
public record CreatePersonCommand : IRequest
And in PersonCommandHandler
, IRequestHandler
would be like this :
public class PersonCommandHandler: IRequestHandler<PersonCommandHandler>
And then in your handle
method :
public async Task<Unit> Handle(CreatePersonCommand request, CancellationToken cancellationToken)
{
// Some Code
return Unit.Value;
}
Generally speaking, if a Task based method does not return anything you can return a completed Task
public Task Handle(CreatePersonCommand message, CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
Now, in MediatR terms a value needs te be returned. In case of no value you can use Unit
:
public Task<Unit> Handle(CreatePersonCommand message, CancellationToken cancellationToken)
{
return Task.FromResult(Unit.Value);
}
or, in case of some async code somewhere
public async Task<Unit> Handle(CreatePersonCommand message, CancellationToken cancellationToken)
{
await Task.Delay(100);
return Unit.Value;
}
The class signature should then be:
public class CreatePersonHandler : IRequestHandler<CreatePersonCommand>
which is short for
public class CreatePersonHandler : IRequestHandler<CreatePersonCommand, Unit>