Q:

How to avoid duplication of code related to shared entities in the repository pattern?

I'm building a repository for a large CRM schema that has a high number of relations between entities.
Some of the entities are referenced by almost all entities, e.g. Person and Company.
Where I have an aggregate root such as Order, that addresses Order Header, Order Lines etc. In the case where the Order is from a new Customer, I need to insert a Company and a Person record at the same time... so far so good.
The difficulty is that this is the situation with very many other aggregate roots.
I don't want to have a private method insertPerson(IPerson) in every single repository implementation.
I have a Customer repository that already has public InsertCustomer(ICustomer) method, which persists a Company and a person record. But my reading indicates that repositories shouldn't depend on each other.
If this is a case where it is okay for repositories to depend on each other, what is the best way to go about it? Should I inject the Customer Repository into the Order repository constuctor, pass it as a parameter to the methods that need it, or never commit this evil and duplicate the identical code in all repositories, in case those repositories need to specialise that code for their specific contexts?

A:

This sounds like an area that Service Layer might come in handy.  You could inject the repositories in the service layer and that way each repo won't depend on the others, and the service can coordinate all of the inserts for a given operation across aggregates.
Details of your implementation might also guide you depending on the extent to which you're relying on an ORM and need to take into account the atomicity of the repository operations. Without knowing more about that this advice may be less than useful.  

