2009-11-11 110 views
1

這裏的情況是:國際奧委會在複雜的環境中

ICategorized所使用的ICategoryService管理類別。

public interface ICategorized 
{ 
    ICategory Category { get; set; } 
} 

然後一些類實現ICategorized

public class Cart : ICategorized 
{ 
    ... 
    ICategory Category { 
     get { 
      return _categoryService.GetItemCategory(...) 
     } 
     set { 
      _categoryService.SetCategoryForItem(...); 
     }; 

    } 

    ... 
} 

那麼,設置_categoryService實現的最佳解決方案是什麼? 通過構造函數或屬性注入?

構造函數的使用可能導致非常複雜的構造像

public class Cart : ICategorized. ITagged, ISecured, IMediaSupport { 
    public Cart(ICategoryService cs, ITagService ts, ISecurityService ss, IMediaService ms) {...} 

    ... 
} 

我懷疑這是一個不錯的設計。有任何想法嗎?


你會有什麼建議嗎? 我可以給ICServiceService負責CartService,但在這種情況下,我不能使用Lazy加載。像

public class CartService : ICartService { 
public CartService(ICategoryService cs) {...} 

... 

} 

回答

4

我贊成構造函數注入屬性注入,主要是因爲它明確了組件需要什麼服務。如果你使用IoC容器,你不必擔心構造函數變得太複雜,因爲你永遠不必使用構造函數,只有容器可以。

屬性注入可以用於非必需的服務。

順便說一下;一般來說,很長的構造函數簽名可能意味着你的類沒有遵循單一責任原則,也許它應該被重構爲兩個或更多的獨立類。

+0

+1會添加一個答案,但是總結得非常好。 – eglasius 2009-11-11 16:53:45