Is it ok for entities to access repositories?

it’s not a horrible violation of DDD it’s a horrible violation of… well… it’s just plain horrible (i say this tongue in cheek) :).

First off, your entity becomes dependent on having a repository… that’s not ideal.
Ideally you’d want to have your repository create the Person and then assign it everything it needs to be effective in the current domain context.

So when you need a Person, you’ll go personRepository.GetPersonWithDefaultEmployer() and get back a person which has default employer populated. The personRepository will have a dependency on an employerRepository and use that to populate the person before returning it.

PersonReposotory : IPersonRepository
{
    private readonly IEmployerRepository employerRepository;

    //use constructor injection to populate the EmployerRepository
    public PersonRepository(IEmployerRepository employerRepository)
    {
        this.employerRepository = employerRepository;
    }

    public person GetPersonWithDefaultEmployer(int personId)
    {
        Person person = GetPerson(personId);
        person.Employer = employerRepository.GetDefaultEmployer(personId);
        return person;
    }
}

Leave a Comment