I asking a question on Stackoverflow earlier and someone pointed me to a previous post of his, He states that injecting a dependency into an entity violates the Single Responsibility Principle.
To save you clicking the link and give some context here is the entity being discussed
public class MyEntity
{
private readonly IValidatorFactory _validatorFactory;
public MyEntity(IValidatorFactory validatorFactory)
{
_validatorFactory = validatorFactory;
}
//Entity Properties Removed For Clarity
public void Validate()
{
if(_validatorFactory == null)
{
throw new ArgumentNullException("Validator Factory was null, cannot validate this item");
}
var validator = _validatorFactory.GetValidator(this.ItemTypeId);
valid = validator.Validate();
}
}
I would have thought that having the IValidatorFactory abstracting the validation type from the entity was exactly what the SRP was about. It passes off the validation concerns to another class. It also adheres to the Open/Closed principal and allows for polymorphism/extending rather than editing existing client code.
To have any real value here, the entity must require different types of validation based on some value, which is what happens when this.ItemTypeId
is used to obtain the correct IValidator reference.
Is this a complete misunderstanding of SOLID principals?
//edit
The question flagged as a possible duplicate does not really answer this. Entities are classes and should encapsulate their own validation, otherwise you are heading into anemic domain model anti pattern territory. I am specifically asking if by having a dependency controlling the validation, am I going against SOLID principals.