I have read a couple of books and articles on MVC, and come across the repository pattern and the services layer.
Should a controller be able to get entities through the repository pattern, or must it retrieve data from the services layer?
Edit: I have code in the services layer that looks like this
public UserInfo GetModel(int userInfoID)
{
return userInfoRepo.Get(userInfoID);
}
public UserInfo GetUserByPortalID(string portalID)
{
return userInfoRepo.GetByPortalID(portalID);
}
public UserInfo GetModelByUserName(string username)
{
return userInfoRepo.GetByUserName(username);
}
If a method in a service only calls another method in repository, is it necessary to have the controller go through the service?
@Service annotates classes at the service layer. @Repository annotates classes at the persistence layer, which will act as a database repository.
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.
The Repository-Service pattern breaks up the business layer of the app into two distinct layers. The lower layer is the Repositories. These classes handle getting data into and out of our data store, with the important caveat that each Repository only works against a single Model class.
Repository pattern is one of the preferred patterns to apply in an application because it allows programmers to integrate all of the fundamental data operations related to an entity in one main class. Without this pattern, developers would need to create multiple classes for each entity with the same logic.
In layered application architecture there's a fundamental rule that says that you must never bypass a layer. If you query your repository straight from your controller, you would be violating that rule.
So what? you may say. What if the service layer adds no value? Well, it might in the future...
You can choose to break the rule, but then it wouldn't be a layered application any more. That may be okay too - there are other good (even better) application architectures available, but I think that first you should make a decision regarding the overall architecture, and then you stick with that decision. Otherwise you'll end up with spaghetti code - we call it lasagna when it's a layered application :)
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