Is it ok for entities to access repositories?

user101945 picture user101945 · May 6, 2009 · Viewed 8.1k times · Source

I've just started working with DDD, so maybe this is a silly question...

Is it ok for an entity to access a repository (via some IRepository interface) to get a value at runtime? For example, I want to enforce a "default" selection for a property:

class Person {
    private Company _employer;

    public Company Employer {
        get { return _employer; }
        set { 
            if(value != null) {
                _employer = value;
            } else {
                _employer = employerRepository.GetDefaultEmployer();
            }
        }
    }

    ...
}

My question is whehter doing something like this is a horrible violation of DDD principles. And if it isn't, my next question would be what it the best way to provide the repository to use? Should it be supplied when the Person object is created?

Thanks, P

Answer

lomaxx picture lomaxx · May 6, 2009

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;
    }
}