我是DDD新手,所以如果我没有正确使用这些术语,请原谅。
我使用的是C#、MS/SQL和NHibernate。
我有一个类调用付款,这个付款有一个PaymentCurrency,其中每个都是数据库中的一个实体。
好的。在我的域名模型中,我希望能够创建付款作为
Payment p = new Payment( 100 ) // automatically uses the default currency (defined in the db )或
Payment p = new Payment( 100, Repository.GetCurrency( "JPY" ) ) // uses Yen defined in the db.但在我看来,为了用dfault货币初始化域对象,我需要用持久性知识污染域模型。即,在我可以完成默认支付构造器之前,我需要从db加载默认支付对象。
我所想象的构造器类似于
public Payment( int amount ) {
Currency = Repository.LoadDefaultCurrency(); // of cource defualt currency would be a singleton
}
public Payment( int amount, Currency c ) {
Currency = c; // this is OK since c is passed in from outside the domain model.
}谢谢你的建议。
发布于 2009-12-12 22:00:23
我不认为有一个完美的解决方案来解决这个问题,但是你可以通过将默认的货币(和类似的属性)存储在其他类中来避免将持久化代码放到域类中。"DomainDefaults"),并从逻辑上位于域对象“上方”的另一段代码中初始化它。当然,您必须确保在创建任何域对象之前调用了初始化代码。如果没有初始化,它可能会抛出一个异常,这样你至少可以很容易地捕捉到这个异常。
所以构造函数变成了
public Payment( int amount )
{
Currency = DomainDefaults.DefaultCurrency;
}在初始化NHibernate后不久的某个地方,您会调用:
DomainDefaults.DefaultCurrency = Repository.GetCurrency("JPY")发布于 2009-12-12 22:07:00
我不明白为什么这和坚持有任何关系。
如果我用Java编写这段代码,我会从应用程序的语言环境中获取默认货币。
This SO question告诉我,CultureInfo是C#的等价物。也许你应该在你的设计中尝试一下,去掉像"JPY“和persistence这样的字符串。
发布于 2009-12-12 21:55:24
你的答案应该是依赖注入。
充分利用它,不要用配置来贬低模型。如果您需要创建具有所需金额和货币的付款-只需执行以下操作:
var currency = injectedCurrencyRepository.GetByName("JPY");
var p = new Payment(100.00m, currency);不要假设默认货币。
或者在最糟糕的情况下,你可以添加inteface:
public interface ICurrencyProvider {
Currency GetCurrency();
}
// Implment the default:
public class DefaultCurrencyProvider : ICurrencyProvider {
public Currency GetCurrency() {
return new Currency("AUD");
}
}
// And the Payment constructor will look like:
public Payment(decimal amount, ICurrencyProvider currencyProvider) {
c = currencyProvider.GetCurrency();
}因此,您可以(使用Windsot、Unity或其他任何工具)默认地将货币提供者注入实例化支付方法中:
var p = new Payment(100.00m, defaultCurrencyProvider);https://stackoverflow.com/questions/1893457
复制相似问题