簡體   English   中英

領域驅動設計問題

[英]Domain Driven Design question

我是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貨幣初始化我的域對象,我需要使用持久性知識來污染域模型。 即在我完成默認的Payment Constructor之前,我需要從db加載Default Payment對象。

我想象的構造函數就像是

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

謝謝你的建議。

我認為沒有一個完美的解決方案,但你可以通過將默認貨幣(和類似的屬性)存儲在其他類(例如“DomainDefaults”)並將其初始化來避免將持久性代碼放入域類中另一段代碼,邏輯上位於域對象“上方”。 當然,您必須確保在創建任何域對象之前調用初始化代碼。 如果沒有初始化,它應該拋出一個異常,所以你至少可以很容易地捕獲它。

所以構造函數變成了

public Payment( int amount )
{
   Currency = DomainDefaults.DefaultCurrency;
}

在初始化NHibernate之后的某個地方,你會打電話給:

DomainDefaults.DefaultCurrency = Repository.GetCurrency("JPY")

我不明白為什么這與持久性有任何關系。

如果我用Java編寫這個,我會從應用程序的Locale中獲取默認貨幣。

這個問題告訴我CultureInfo是C#的等價物。 也許你應該在你的設計中嘗試,並留下像“JPY”和持久性的字符串。

你的答案是依賴注入

使用它並且不要使用配置來規范模型。 如果您需要創建具有所需金額和貨幣的付款 - 只需這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM