这是我遇到的一个问题的简单示例,它与此处和其他地方提出的有关 DDD 的一些想法不相符。
假设我有一个创建/操纵一个人的 ASP.NET MVC 3 站点。控制器访问应用程序服务层 (PersonService),后者又使用域实体 (EF 4 POCO) 和 PersonRepository 进行更改并持久化它们。为了简单起见,我在这里省略了所有接口。在这种情况下,Person 是根,为简单起见,只有电子邮件地址(还假设电子邮件不是不可变的并且可以更新)。
选项 1:尝试坚持 [我的理解] DDD 的基础知识,其中与实体直接相关的行为被实现为实体的一部分(Person 实现 AddEmail、ChangeEmail 等)。除了 Add* 方法之外,唯一的问题是 Person 需要了解上下文或实体框架部分(这将消除任何持久性无知)或需要使用“服务”或存储库来标记修改后的电子邮件。
// Person Service
public class PersonService {
// constructor injection to get unit of work and person repository...
// ...methods to add/update a person
public EmailAddress AddEmailAddress(int personId, EmailAddress email)
{
Person p = personRepository.Find(p => p.Id == personId).First();
p.AddEmail(email);
uow.SaveChanges();
return email;
}
public EmailAddress ChangeEmailAddress(EmailAddress email)
{
Person p = personRepository.Find(p => p.Id == personId).First();
p.ChangeEmail(email);
// change state of email object here so it's updated in the next line???
// if not here, wouldn't the Person entity have to know about the context
// or use a service?
uow.SaveChanges();
return email;
}
}
// Person Repository
public class PersonRepository
{
// generic repository implementation
}
// Person Entity
public class Person
{
public string Name { get;set; }
public IEnumerable<EmailAddress> EmailAddresses { get;set; }
public void AddEmail(EmailAddress email)
{
this.EmailAddresses.Add(email);
}
public void ChangeEmail(EmailAddress email)
{
EmailAddress orig = this.EmailAddresses.First(e => e.Id == email.id);
// update properties on orig
// NOW WHAT? [this] knows nothing about the context in order to change state,
etc, or do anything to mark the email add updated
}
}
// Email
public class EmailAddress
{
public string Email { get;set; }
public bool IsPrimary { get;set; }
}
选项 2:让人员服务使用存储库来添加/更新电子邮件地址,并且不对人员实体实施该行为。这在多对多关系的情况下要简单得多(例如,地址,需要更新两个表才能完成工作),但是模型变得“贫血”,只是一堆 getter 和 setter。
// Person Service
public class PersonService {
// constructor injection to get unit of work and person repository...
// ...methods to add/update a person
public EmailAddress AddEmailAddress(int personId, EmailAddress email)
{
Person p = personRepository.Find(p => p.Id == personId).First();
personRepository.AddEmail(personId, email);
uow.SaveChanges();
return email;
}
public EmailAddress ChangeEmailAddress(EmailAddress email)
{
personRepository.ChangeEmail(email);
uow.SaveChanges();
return email;
}
}
// Person Repository
public class PersonRepository
{
// generic repository implementation
}
// Person Entity
public class Person
{
public string Name { get;set; }
public IEnumerable<EmailAddress> EmailAddresses { get;set; }
}
// Email
public class EmailAddress
{
public string Email { get;set; }
public bool IsPrimary { get;set; }
}
无论如何,对此有什么想法吗?
谢谢,布赖恩