Should a Controller ever need to call a Repository directly, or should it always run though the service layer? Or are there other options?
@Controller Annotation. @Service annotation is used with classes that provide some business functionalities. @Repository Annotation is used to indicate that the class provides the mechanism for storage, retrieval, update, delete and search operation on objects.
Yes, it is a bad practice. Controller should be used only to control the flow of your application, get input from client apps, call service and pass data to the view (JSON/HTML/XML/etc). Repository/DAO should be used to retrieve/persist the data without knowing any business logic.
The unit of work class serves one purpose: to make sure that when you use multiple repositories, they share a single database context. That way, when a unit of work is complete you can call the SaveChanges method on that instance of the context and be assured that all related changes will be coordinated.
Repository layer is implemented to access the database and helps to extend the CRUD operations on the database. Whereas a service layer consists of the business logic of the application and may use the repository layer to implement certain logic involving the database.
If you have a service layer and your're using it in a way that abstracts the business logic away from the repository (as you should with a service layer) then no, your controllers should only be making calls to the service methods. The service layer will then be the coupling to the repo.
Further to Mayo's answer: the model are the data classes that will be passed throughout the application (repo, service and UI/controllers) so the UI/web layer should 'operate' on them just like the other layers will.
I think if you implement a service layer in the context of Fowler's definition and the modern aspnet mvc adaptions, then you should have your controller actions designed as very small and lightweight methods, calling the 'meaty' business logic from your service layer.
EDIT: I guess i wasn't clear: I'm not saying having a service layer is the only option, just trying to answer part of the question pertaining to the case where you do use a service layer. Agreed, a service layer is not always necessary, especially for smaller projects.
You don't always need a service layer - in simple situations it is just over engineering the solution. It's fine for controller to call repository. But, if you see your controllers bloating with logic, or you are repeating yourself in controller actions, then look at putting a service between the controller and repository, and move some of the logic from the controller to ther service layer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With