Deb
Deb

Reputation: 401

C# DDD - Domain Object Creation

I have started learning and creating CQRS with event sourcing using C#. 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?

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;
    }
}

Upvotes: 1

Views: 1492

Answers (2)

berhalak
berhalak

Reputation: 677

I think this is one way to approach DDD persistence problem.

See https://vaughnvernon.co/?p=879, V. Vernon does the same thing.

Upvotes: 0

Alan G
Alan G

Reputation: 86

DTO is the wrong thing to use here. You are introducing an undesirable linkage between DTO's and domain objects and they evolve differently. You can imagine that domain objects may evolve to take more arguments or DTO's will need more properties.

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.

Upvotes: 5

Related Questions