2015-02-24 28 views
1

我正在使用DDD。實體VS Id作爲參數

我有以下接口:

interface ICustomerRepository 
{ 
    void Disable(int customerId); 
} 

interface ICustomerService 
{ 
    void Disable(int customerId); 
} 

該應用程序將在一個WebService工作。

我想知道,我應該使用id作爲參數還是整個Customer實體?

每種方法的優缺點是什麼?

回答

5

嗯,事實是,這種行爲不應該在存儲庫上。行爲應該放在實體中。

但是,您的應用程序服務合約應該可能免除域類。

例如

//Application service (runs in a transaction) 
public void Disable(int customerId) { 
    var customer = this.customerRepository.FindById(customerId); 
    customer.Disable(); //execute business logic 
    this.customerRepository.Save(customer); //persist the state 
} 
0

使用CudtomerId是一個更好的主意。因爲當你傳遞Customer實體(通常我們使用按值傳遞)時,它會複製它並使用它;這是默認情況下將是一個空的實體。
所以,我認爲你的方式是最好的。

+0

Customer是一個引用類型(class),默認情況下它是通過引用傳遞的。 但我不認爲這是一個問題。 – 2015-02-24 19:50:05

1

雖然plalx提供的答案可能是完成這一任務的純粹的方式我還發現一個完整的保存在某些情況下可能會矯枉過正。

如何在兩者的混合物:

interface ICustomerRepository 
{ 
    void SaveDisable(Customer customer); 
} 

interface ICustomerService 
{ 
    void Disable(int customerId); 
} 

然後代碼可能是:

public void Disable(int customerId) { 
    var customer = _customerRepository.Get(customerId); 
    customer.Disable(); 
    _customerRepository.SaveDisable(customer); 
} 

這將需要一個非常謹慎的附加功能,因爲我們明確什麼是持續存在。

+1

有沒有優勢? – plalx 2015-02-25 12:36:02

+0

如果有一個聚合需要不必要的數據訪問,那麼是的,這是有優勢的;否則我不會這樣做:) – 2015-02-25 12:58:35

+1

是不是過早的優化?你有完整的保存性能問題嗎?我想這很好取決於變化檢測所採用的策略...... – plalx 2015-02-25 13:02:12