DDD: entity's collection and repositories

前端 未结 7 1172
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 12:04

Suppose I have

public class Product: Entity
{
   public IList Items { get; set; }
}

Suppose I want to find an item with max someth

7条回答
  •  走了就别回头了
    2021-01-30 12:31

    Having an Items collection and having GetXXX() methods are both correct.

    To be pure, your Entities shouldn't have direct access to Repositories. However, they can have an indirect reference via a Query Specification. Check out page 229 of Eric Evans' book. Something like this:

    public class Product
    {
        public IList Items {get;}
    
        public int GetMaxItemSmth()
        {
            return new ProductItemQuerySpecifications().GetMaxSomething(this);
        }
    }
    
    public class ProductItemQuerySpecifications()
    {
       public int GetMaxSomething(product)
       {
          var respository = MyContainer.Resolve();
          return respository.GetMaxSomething(product);
       }
    }
    

    How you get a reference to the Repository is your choice (DI, Service Locator, etc). Whilst this removes the direct reference between Entity and Respository, it doesn't reduce the LoC.

    Generally, I'd only introduce it early if I knew that the number of GetXXX() methods will cause problems in the future. Otherwise, I'd leave it for a future refactoring exercise.

提交回复
热议问题