I'm a little unsure as to what code belongs in the services and what belongs in the controllers.
Lets say I'm creating a website that requires a fine grained level of permissions (e.g. a user has permissions based on their user level (if they're currently logged in) determining whether they can view, edit, add entities and each entity has it's own set of requirements).
The process is pretty much the same for all entities:
- Get the current user, either a registered one or an anonymous one
- Get the requested entity
- Check that it is not null
- Check it isn't locked by the system
- Check that the user has permissions to view/edit on the entity, as well as all parent entities
So, what should go where?
Right now, my controller makes a call to the service to get the entity and passes in the user (or null for anonymous).
The service makes a call to the repository which gets the entity by the id. Then it makes sure that the user has permission to view it. The code is basically:
// Controller
public ActionResult Get(int id)
{
string error;
var entity = EntityService.Get(id, GetUser(), out error);
if(entity == null)
// Display error
else
// Display entity
}
// Service
public Entity Get(int id, User user, out string error)
{
var entity = Repository.Get(id);
// null check
// permissions check
// if it passes, return the entity, otherwise assign error and return null
}
I don't really like this way of doing it because if I need to do something like redirect the user or display a custom view, I can't just return an error string, I need an enum or something to tell me exactly why the Get
failed so I can handle the case properly. Plus (and I'm not sure if this is actually considered a bad thing) whatever is going on in the services method is hidden from the controller.
Any suggestions on a better design?