【发布时间】:2013-05-28 18:50:54
【问题描述】:
在域模型中,当您有一个实现 Validate 方法的模型类并且在此方法中您将 BrokenRules 添加为 BusinessRule 对象并且它们都具有属性和规则消息时,本地化这些消息的最佳方法是什么?
【问题讨论】:
标签: .net validation domain-driven-design
在域模型中,当您有一个实现 Validate 方法的模型类并且在此方法中您将 BrokenRules 添加为 BusinessRule 对象并且它们都具有属性和规则消息时,本地化这些消息的最佳方法是什么?
【问题讨论】:
标签: .net validation domain-driven-design
破坏规则/实体验证
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
var validationResults = new List<ValidationResult>();
//-->Check first name property
if (String.IsNullOrWhiteSpace(this.FirstName))
{
validationResults.Add(new ValidationResult(Messages.validation_CustomerFirstNameCannotBeNull,
new string[] { "FirstName" }));
}
//-->Check last name property
if (String.IsNullOrWhiteSpace(this.LastName))
{
validationResults.Add(new ValidationResult(Messages.validation_CustomerLastNameCannotBeBull,
new string[] { "LastName" }));
}
return validationResults;
}
您可以让您的实体实现 IValidatableObject。这是 System.ComponentModel.DataAnnotations 的一部分。 您仍然可以看到 resx 文件可以这样使用。或者您只需围绕您在应用程序启动时读取的 xml 文件制作自己的静态包装器。
【讨论】:
在我看来,本地化属于 UI。您甚至有这个问题的事实可能表明您 overgeneralized 您的模型并引入了诸如 Validate 和 BusinessRule 之类的概念。现在,Presentation 关注“渗透”到您的域代码中。如果您使用通用语言,您的代码看起来更像
bool isDelinquent = order.IsDelinquent();
域显然不对用户友好和本地化消息等 UI 问题负责。相反,您可能有以下几点:
List<BusinessRule> brokenRules = order.Validate(){
...
brokenRule = new BusinessRule("Sorry this is order is delinquent");
// what if I want this message in Italian?
// would this even fit into error text box?
// should delinquency unit test rely on 'magic string' error message?
...
}
【讨论】:
您遇到的问题是您的域代码可能未在 UI 附近运行。话虽如此,如果代码在服务器(例如消息总线端点)上运行,那么任何异常都会成为业务流程的一部分。
对于任何确实在了解前端语言的情况下运行的东西,我建议使用资源文件。它们真的会是最简单的。
除了可能需要特定例外或某些编码/查找系统之外,
【讨论】:
您绝对可以在域中拥有消息。但它们应该是特定于域的,并告诉客户端什么是错误的或什么是无效的(通常是响应客户端的错误和验证消息)。 看看那里最好的 DDD 示例之一http://msdn.microsoft.com/es-es/architecture/gg189193
他们在域中使用消息,例如:
throw new InvalidOperationException(Messages.exception_BankAccountCannotDeposit);
或
originAccount.WithdrawMoney(amount, string.Format(Messages.messages_TransactionFromMessage, destinationAccount.Id));
如您所见,您可以在 Domain 项目中使用 resx 文件,并使用它们将异常和其他业务消息等消息存储回客户端
希望这对您有所帮助。 干杯
【讨论】: