Search code examples
domain-driven-designentityseparation-of-concernsddd-repositoriesdomainservices

Persistence encapsulated via the domain, or persistence via the Repository?


If my Domain Model is not supposed to know/care about the Repository, then how does some behaviour like .UpdateOrder(...), that encapsulates a CRUD-Update, interface with the Repository? Through a Domain Service?

Ok, then my Repository has an effective CRUD-Update that's used in conjunction with my .UpdateOrder(...). That's fine. But i don't want someone to use the Update method on the Repository, i want them to go through the behaviour on the Entity (use UpdateOrder() instead). I'd prefer that in likeness to the way my Domain Model satisfies invariants - by it's design (private set properties, etc) - my Repository not expose an alternate method to "updating"/persisting the Entity.

Is this simply a access modifier problem that is solved by me not having the Update method in the Repo public. Or is there a 'better' answer? Please help me DDD ninjas.


Solution

  • The strict sequence in DDD would be:

    var entityRepository = MyServiceLocator.Get<IEntityRepository>();
    var myEntity = entityRepository.Load(<some criteria>);
    myEntity.Change(something);
    entityRepository.Save(myEntity);
    

    The repository is always responsible for detecting/persisting all of the changes within the entity.

    (btw, I'm assuming that your entity is an aggregate root)