I know it’s generally considered a bad practice to inject Services in an Entity (through a constructor or a setter), and to have the entity keep a reference to it.
But is it ok to transiently hand a Service to an entity when invoking a method?
For example, say I want to version the name field of an Entity, and have a VersionService create a new version every time setName() is called, I could do:
public class Entity
{
public void setName(String name, VersionService service)
{
this.name = name;
service.addVersion(this, name);
}
}
What I like in this code, is that the setName() method can’t be called without providing a VersionService, thus forcing the desired behavior. It’s also easily testable, by mocking the VersionService.
I’ve found an example of this approach in a post on the double dispatch pattern by Jimmy Bogard.
But from some discussions on Stack, I thought that the general consensus was to avoid having any dependency on Services in the Domain Model.
Any thought on the subject?
As far as Domain services are concerned, I’d be curious to know the arguments against using them in entities. Domain services are first class domain objects contained in the ubiquitous language. There are plenty of scenarios where it is justified for logic located in an entity to call logic located in a domain service, just like it would call another entity.
Paragaph 3 in this article has a good example of this.