How to initiate domain services in DDD and Entity Framework?

I have a Domain model below that needs two domain services to check the database state and generate the date time now for the sake of testability:

public class Person 
{
    public string Name { get; private set; }
    public string Family { get; private set; }
    public string NationalId { get; private set; }
    public string CreatedAt { get; private set; }
 
    public Person(string name, string Family, string nationalId, IUniqeService us, IDateTimeProvider dtp )
    {
        Name = name; 
        Family = family;

        if (!us.IsUniqueInDB(nationalId))
        {
            throw new DominException("National Id is duplicated");
        }

        NationalId = nationalId;
        CreatedAt = stp.GetNow();
   }

}

Currently, I am using EF as my ORM and it needs a constructor to fetch the data from DB and provide it as an instance of the Person class. So, I want to know the available and best practices to inject these dependencies into my class.

I know about the builder and factory design patterns to bypass the unnecessary dependencies from contractors. But what if some of them are required in constructors too?

  • 2

    Don’t ask “what is best…” questions. They will be closed as opinionated. What you actually want to know is “how to”. Nobody would intentionally give you sub par answers to that. Then you can choose which one fits your specific case best.

    – 

  • To your question: I have never seen anyone injecting services into a domain model like that before. If you create it new in order to add it to the db, then you would like to use your time service. But if it is already in db and you create an instance from persisted data, you would want the persisted time stamp, wouldn’t you? Also: I have been consulted to do validation outside the model.

    – 

  • So, I am talking in DDD concept

    – 

Leave a Comment