I have an annoying code smell in my asp.net core api that I am passing around, and I can't come up with a way to fix.
In an MVC controller action, usually there is a very straight forward logic, at least in my case.
- Validate model (before calling the action)
- Query relevant data
- Do business logic
- Send response
Now in some actions, the logic needs to be a little bit more complex.
Sometimes, model validations requires a query to the database.
Using FluentValidation it's usually enough just to inject the required dependency, and use it to query the database - and then have the controller query other relevant data.
Now this is where it all gets messed up, I have many model validations that require the same data as the controller action.
so, what I do at the moment, in these cases seems like a code smell to me.
- Validate Model, querying only data that isn't required by the controller
- Query relevant data, and validate in the controller
- Do business logic
- Send response.
I don't like the idea of validating data inside the controller, since it often results in a 60 line action, most of which is model validation, and it breaks SOLID which might get confusing as the app grows.
The option of querying the data twice seems like an extremely bad option and frankly I see no reason to actually choose it.
So the question is basically, how do you suggest validating BindingModels against the database?
The ideal method to me seems like somehow injecting the queried data to the AbstractValidator implementation (or any other class responsible for validation), and to the controller, and that way I get to keep the original logic, without querying the same data twice. However, I am pretty sure actually implementing it is way worse.