Search code examples
clean-architecture

Clean Architecture and entity's dependency injection


Considering the Clean Architecture's domain, does the entities can receive an external object trough a dependency injection to validate it's fields? This is acceptable? At this moment I think no, because it seems breaking the dependency rule despite the abstrations.


Solution

  • You can inject a validator into an entity and still honor the dependency rule. You just have to specify an interface,

    public interface OrderValidator {
        public void validate(Order order)
        // maybe more fine grained methods
    }
    

    implement it in an outer layer (gateways)

    public MyOrderValidator implements OrderValidator {
       // ...
    }
    

    and pass it to the entity.

    public class Order {
      
        public Order(OrderValidator v){
           // save to private field
        }
    }
    

    BUT this design means that you pull validation logic out of the entity and you put it somewhere else. This leads to an anemic domain model.

    Usually a domain entity contains the validation rules it needs to ensure it's state.

    If you have validation rules that belong to multiple entities, like an aggregate in DDD, you should use a domain service. When you want to inject a dependency into a domain entity it must be injected whenever an entity is created. You usually create entities within use cases by simply calling their constructor. Either the use case passes the dependency or you create a factory that is responsible for injecting dependencies. But also repositories return entities and also must inject the dependencies. When using a factory the repositories can use the factory as well.

    Finally it might also be easier to inject a dependency in a domain service and let the domain service do the validation. But as I said above: This can easily lead to an anemic model and you should always try to prevent this.