I am using the C# MediatR library to implement a mediator pattern to send commands and queries from my controller. As I am new to this pattern so I have been watching some online tutorials where I saw that in some cases the Mediator Query
or Command
classes have been passed as parameters to controller action methods and forwarded as it is to the MediatR while in some tutorials there is a separate view model passed into the controller action methods method, which is first mapped to command or query class and then forwarded to the MediatR.
Which approach is considered better, passing Command/Query to controller action directly or using a view model instead? Couldn't find any relevant answer yet. Any help is highly appeciated
Command being passed into controller action parameter
[HttpPost]
public async Task<IActionResult> Login(LoginUserCommand loginUserCommand)
{
var User = await _meditr.Send(loginUserCommand);
return View();
}
ViewModel used in the controlleraction parameter
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel loginViewModel)
{
var authenticateUserCommand = _mapper.Map<LoginUserCommand>(loginViewModel);
var User = await _meditr.Send(authenticateUserCommand);
return View();
}
CodePudding user response:
I think you should first understand the difference between ViewModel
and DTO
. In most cases, the naming is wrong. A command in this context is technically a DTO
. But it also represents something that has a special meaning in the business domain - something that shall happen, i.e. a command to be executed in the system.
Read this post to better understand : https://stackoverflow.com/questions/1431445
But about your main question When you use Mediatr
.
In fact, your controller
only acts as an interface or bridge between the user and the program logic,
and only needs to establish this connection, so it receives the desired command or Dto
, and the validation operation is
the responsibility of your command
and handler
. In this scenario, if you receive the data in a different way and map it to a command,
it is practically of no use and is considered overtime because you are not going to do any validation on your controller.
So this is a better option
[HttpPost]
public async Task<IActionResult> Login(LoginUserCommand loginUserCommand)
{
var User = await _meditr.Send(loginUserCommand);
return View();
}
If you are looking for a good example, I recommend this repository :