实体可以访问存储库吗? [英] Is it ok for entities to access repositories?

查看:73
本文介绍了实体可以访问存储库吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用DDD,所以也许这是一个愚蠢的问题...

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

实体是否可以访问存储库(通过某些方法) IRepository接口)在运行时获取值?例如,我要对属性强制执行默认选择:

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

    ...
}

我的问题是做这样的事情是对DDD原则的可怕违反。如果不是,那么我的下一个问题是提供使用该存储库的最佳方法是什么?创建Person对象时是否应该提供它?

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?

谢谢,
P

Thanks, P

推荐答案

可怕的违反DDD的行为,是对……的可怕的侵犯。。。这简直太可怕了(我说这是舌头在脸):)。

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) :).

首先,您的实体变得依赖于拥有存储库了……这是不理想的。
理想情况下,您想让存储库创建Person,然后为其分配在当前域上下文中有效所需的一切。

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.

因此,当您需要一个Person时,您将转到personRepository.GetPersonWithDefaultEmployer()并找回拥有默认雇主的人员。 personRepository将依赖loyerRepository,并在返回之前使用它来填充此人。

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

这篇关于实体可以访问存储库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆