Search code examples
domain-driven-designrepository-patternfactory-patternddd-repositories

DDD repository and factory


In my application a few layers. In this topic will focus on Domain and Infrastructure layers.

I have repository interface ClientRepositoryInterface in Domain layer. And I have implementation of this interface ClientRepositoryImpl in Infrastructure layer.

But to reconstitute the object in the middle of the cycle of its existence I need factory(ReconstitutionClientFactory). Call the factory will be in the repository. The book by Eric Evans is described as a normal practice.

But where this factory(ReconstitutionClientFactory) should be located? In Domain or in Infrastructure layer?

I think in Domain... BUT! But then the lower layer will directly call a higher layer! This is wrong, but how to do right?


Solution

  • First of all, the layers approach is kinda obsolete. When talking layers think 'context', who's on top of who isn't important.

    The repository is in charge of restoring an object. A factory just creates a new object. Note the different semantics. The repository knows how saving/restoring to/from persistence is done and that depends on the storage and the method of access.

    So, everything is done inside the repository i.e in the Infrastructure. If you serialize things, then you need just to deserialize back (this is how a document db does things anyway). If you're using an ORM or store things in tables then you'll do all the query required to get the data and repopulate the object. An ORM is the easiest way since it can use reflection to populate private properties. In this case the ORM itself is the factory.

    One more thing, restoring, while technically can be done by a domain factory, it isn't the factory's purpose to do that because it breaks the layer boundaries. We want to keep everything persistence related in the Infrastructure.