After reading this article about validating with service layer I have some doubts.
First: Is it all right to pass the whole model view to the service as shown in article ? I have seen some example where rather then passing whole model that is used by controller (like bool success = _productService.CreateProduct(productModel)) they called services like this:
bool success = _productService.CreateProduct(productModel.Name, productModel.Category, productModel.Cost)
What are pros/cons of both approaches ?
Second: I can see the logic in using same service for validating model and doing the actual work. On the other hand it means that the service will have to deal with 2 concerns: data validation and data processing. That means more code in the same service and worse testability, right ?
So instead of example code above would it be better to have:
bool valid = _productValidationService(productModel);
if(valid){
_productService.CreateProduct(productModel);
//or maybe _productService.CreateProduct(productModel.Name, productModel.Category, productModel.Cost);
}
What are the pros/cons ? Is there something that I don’t see ? What do you use ? What is standard approach ?
I prefer to pass the whole model to the service instead of individual properties to avoid cluttering the methods. As far as the validation logic is concerned you are saying that it has to deal with two concerns: business logic validation and actual saving. I think that those two concerns belong to the service. A consumer of this service shouldn’t be able to call only the save without validating first and perform those two things in the service ensures that this wouldn’t happen. Also the actual saving could be delegated by the service method to one or multiple CRUD repository calls.
So in a controller:
In the article you have linked the following approach is used to initialize the service and pass it the model state so that it writes the errors directly:
so that later you could directly:
This is also a valid and good approach. The only problem is the following line
_productService = new ProductService(...inside a controller which is very bad as it is tightly coupling the controller with a particular implementation of a service. The service should be injected by a DI framework but the problem is passing the ModelState as it would create circular dependency. There are some threads here addressing this issue.