Search code examples
entitydomain-driven-designaggregate

Configure behaviour of DDD aggregate with strategies


I've an aggregate:

public class MyAggregate {

    private Country country;
    private List<SomeEntity> someEntities;

    public SomeEntity getBestMatchingSomeEntity();

}

My problem is, that the behaviour of getBestMatchingSomeEntity() should be configurable depending in the country, so I like to use strategies (simple Spring beans).

Im not sure how to "inject" the strategy in my entity. Normally I would use some kind of selector, but I don't want to inject a service in my entity. Or should I select the right strategy while creating the entity and inject the strategy in the entity? Or is a domain service the way to go?

Thank you!


Solution

  • First thing that pops up in my mind.

    Why don't you have the method that accepts a service like:

    public class MyAggregate {
    
        private Country country;
        private List<SomeEntity> someEntities;
    
        public SomeEntity getBestMatchingSomeEntity(MatchingEntityService service);
    }
    

    Then you define the service as:

     public interface MatchingEntityService {
    
         SearchEntityStrategy strategyFor(Country country);
    
     }
    

    In this way in your aggregate you can use the service without having the problem of injection, and the relatives serialization problems.

    The MatchingEntityService will have the logic to select the right strategy based on the Country and you can keep all the different strategies separated.