如何设计域驱动的设计应用程序服务进行聚合?

时间:2019-12-02 07:39:56

标签: design-patterns architecture domain-driven-design

我是域驱动设计的新手,所以我想问一下将应用程序服务用于聚合根。

我有一个聚合根。

public class Product: AggreagateRoot{
    publis int Id {get; set;}
    publis string Name {get; set;}

    public ICollection<Comment> Comments {get; set;}
    public ICollection<Types> Types {get; set;}
}

注释和类型与产品有关。因此,“注释”或“类型”本身并不意味着任何东西。

因此,我正在为产品创建应用程序服务。

public class ProductService {

    public Product Create(ProductCommand command){
        .....
        ...
    }

    public Product Update(ProductCommand command){
        .....
        ...
    }

}

我是否应该像下面那样在ProductService中添加用于创建和更新注释和类型的方法?

public class ProductService {

    public Product Create(ProductCommand command){
        .....
        ...
    }

    public Product Update(ProductCommand command){
        .....
        ...
    }

    public Comment Create(CommantCommand command){
        var product = _context.Product.Find(command.ProductId);

        product.Comments.add(new Comment(command.message));

        _context.SaveChanges();
        .....
        ...
    }

    public Comment Update(CommantCommand command){
        var comment = _context.Comments.Find(command.Id);

        comment.message = command.message;

        _context.SaveChanges();
        .....
        ...
    }       
}

还是应该为注释和类型创建单独的服务?

1 个答案:

答案 0 :(得分:0)

public class Product: AggreagateRoot{
    public int Id {get; set;}
    public string Name {get; set;}

    public ICollection<Comment> Comments {get; set;}
    public ICollection<Types> Types {get; set;}
}

如图所示,此模式通常称为anemic domain model,通常被认为是反模式。缺少的是行为,即描述此数据结构如何随时间演变的逻辑,存在于应用程序服务代码中,而不是存在于域模型中。

换句话说,您在这里实现的是一个愚蠢的数据包。

我们通常要做的是编写代码,以便域行为在域实体中。应用程序层中的代码仅调用域模型代码。例如:

Create(CommantCommand command){
    var product = _context.Product.Find(command.ProductId);

    product.AddComment(command.message));

    _context.SaveChanges();
    .....
    ...
  

我应该为注释和类型创建单独的服务吗?

应用程序组件只能与聚合根通信。这是扎根的一部分。因此,如果我们假设“注释”和“类型”属于一个集合,则否,则不应为它们提供单独的服务。

如果多个产品共享相同类型,则可以合理地将Type设为自己的汇总。

相关问题