How to avoid persistence logic in a domain model?

My domain model is as follows:

class Group { private List<Person> persons; public void AddPerson(Person p) { persons.Add(p); DoSideEffect() } public List<Person> GetPersons() {...} } 

Now I need to persevere. By DDD, I cannot add any persistence attributes to this class, so XML serializers will not work. BinaryFormatter cannot be used because the format must be readable. I can manually call GetPersons () and save them, but how do I load them? If I call AddPerson (), then a side effect occurs. A side effect can occur only when a person is β€œtruly” added to the domain, and not with constancy.

+4
source share
2 answers

I understand that this post is old, but it still remains unanswered, so here it is:

The key here is that your model is wrong, imo.

The group must be a domain object with a simple read-only collection (members?). The responsibility for retrieving and saving the group belongs to the GroupRepository, which downloads data from the persistence store and restores the object.

For instance:

 public class Group { private Collection<Person> _persons; public Group(Collection<Person> persons) { if (persons == null) throw new ArgumentNullException("persons"); _persons = persons; } public IEnumerable<Person> Persons { get { return _persons; } } public void AddPerson(Person p) { if (p == null) throw new ArgumentNullException("p"); _persons.Add(p); DoSideAffect(); } } public class GroupRepository { public Group FindBy(Criteria c) { // Use whatever technology (EF, NHibernate, ADO.NET, etc) to retrieve the data var group = new Group(new Collection<Person>(listOfPersonsFromDataStore)); return group; } public void Save(Group g) { // Use whatever technology to save the group // Iterate through g.Persons to persist membership information if needed } } 

Use the dependency injection infrastructure (Spring.NET, MEF, Unity, etc.) and create the IGroupRepository interface, which can be entered into the application code to retrieve and save group domain objects.

+3
source

Lack of attributes is not a show stopper; XmlSerializer has a constructor that will run in this model at runtime (but, to be honest, in most cases, the default values ​​are fine), like several other serializers. XML through XmlSerializer is obviously desirable if readability is a problem. See XmlAttributeOverrides . I can also suggest some binary serializers that will work here.

0
source

All Articles