I’m working on a model for an ASP.NET MVC app with DI and an ORM.
Lately, I’ve been looking into the pros and cons of writing all my business logic in a service layer vs placing logic specific to an entity in the entity class itself. Methods declared in the entity classes are obviously called on a specific instance of the entity and can therefore only be called when that instance has been instantiated from a query to the ORM.
Let’s say I have a Product entity and I declare an ApplyDiscount method on it. Given an ID of a product passed in from a controller’s action method, I must first query for an instance of the product using this ID and then call the ApplyDiscount method. But where should the querying code take place? Is it a valid practice to declare a method in my service layer which takes an ID, queries for the Product instance, and then calls ApplyDiscount on that instance? Or should that code go somewhere else?
Ultimately, I’d like to know if having querying code in the service layer and having modification- code of the resulting entities in the entity classes themselves is the common / correct implementation when attempting to avoid a fat service layer & anemic domain model.
Does having the querying code in the service layer defeat the purpose altogether?
It doesn’t defeat the purpose, but you’re ending up migrating functionality (specifically, validation) into the service layer where it shouldn’t necessarily be.
Generally, you’d want for the validation to occur at the earliest possible point; that is, if you’ve been given an invalid ID, you want to make sure that you’ve caught that invalid condition before starting an execution chain all through your logic. Typically, this means performing the query in the controller and passing the resultant object through your service layer; this isolates the functionality of querying up to a high level in your execution chain, and prevents you from having to implement high-level exclusion logic in your service layer (for example, if an entire set of IDs is invalidated, you can perform that validation outside of your service layer, thereby isolating that associated logic and keeping you from needing to do that inside your service layer.
In general, consider the approach to be this: perform object-level validation and deserialization at the earliest point of reference, to migrate your logic as far up out of your service layer as possible, and thereby “thin up” your service layer. There’s a certain amount of flexibility involved here, of course, but as a general rule, it’s a good one.