简体   繁体   English

C#DDD-域对象创建

[英]C# DDD - Domain Object Creation

I have started learning and creating CQRS with event sourcing using C#. 我已经开始使用C#通过事件源学习和创建CQRS。 I checked a lot of samples and in each sample, while constructing domain object all required domain fields are either passed using the constructor or a through a static method to create the domain object. 我检查了很多示例,并在每个示例中,在构造域对象时,所有必需的域字段都使用构造函数或通过静态方法传递来创建域对象。

Should I pass the complete DTO to to the domain object to construct it instead of passing a long list of individual fields which I am getting from my top layer? 我是否应该将完整的DTO传递给域对象以构造它,而不是传递从顶层获得的单个字段的长列表?

public class Student : AggregateRoot
{
    public int ID { get; set; }
    public string  Name { get; set; }

    // Without ID and Name a domain object should not be created

    //Can I write like this?         
    public Student(StudentDto studentDto)
    {
        ID = studentDto.ID;
        Name = studentDto.Name;
    }

    //Can I write like this?
    public Student(int id,string name)
    {
        ID = id;
        Name = name;
    }
}

DTO is the wrong thing to use here. DTO在这里使用是错误的事情。 You are introducing an undesirable linkage between DTO's and domain objects and they evolve differently. 您正在引入DTO和域对象之间的不良链接,并且它们的发展方式有所不同。 You can imagine that domain objects may evolve to take more arguments or DTO's will need more properties. 您可以想象域对象可能演变为采用更多参数,或者DTO将需要更多属性。

In general, you should pass the explicit fields domain object needs in its constructor. 通常,应在其构造函数中传递域对象需要的显式字段。 If you end up having a long list of constructor arguments, either the domain object may be having too many resonsibilities, or you can use the Builder pattern to reduce number of explicit arguments needed. 如果最终的构造函数参数列表很长,那么域对象可能具有太多的责任感,或者可以使用Builder模式减少所需的显式参数数量。

I think this is one way to approach DDD persistence problem. 我认为这是解决DDD持久性问题的一种方法。

See https://vaughnvernon.co/?p=879 , V. Vernon does the same thing. 参见https://vaughnvernon.co/?p=879,V 。弗农也做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM