2011-12-24 158 views
7

我有類,如AccountsController,ProductsController等都從BaseController繼承。 Unity根據需要設置我的服務。這些類也都需要_sequence服務。因爲這是所有類的通用要求,所以我想在BaseController中對其進行編碼。在C調用超級構造函數#

public class AccountsController : BaseController 
{ 
    public AccountsController(
     IService<Account> accountService) { 
     _account = accountService; 
    } 

public class ProductsController : BaseController 
{ 
    public ProductsController(
     IService<Account> productService) { 
     _product = productService; 
    } 


public class BaseController : Controller 
{ 
    public IService<Account> _account; 
    public IService<Product> _product; 
    protected ISequenceService _sequence; 

    public BaseController(
     ISequenceService sequenceService) { 
     _sequence = sequenceService; 
    } 

但我該怎麼做?我應該在每個AccountsController和ProductsController的構造函數中設置對BaseController的調用嗎?

回答

12

你可以連續constructors

public class ProductsController : BaseController 
{ 
    public ProductsController(
     IService<Account> productService) : base(productService) 
    { 
     _product = productService; 
    } 
} 

注意,鏈接BaseController(使用base關鍵字)已經通過了productService參數,堅韌這可以是任何東西。

更新:

可以執行以下操作(差芒依賴注入):

public class ProductsController : BaseController 
{ 
    public ProductsController(
     IService<Account> productService) : base(new SequenceService()) 
    { 
     _product = productService; 
    } 
} 

或者,通過在ISequenceService依賴通過你的繼承類型:

public class ProductsController : BaseController 
{ 
    public ProductsController(
     IService<Account> productService, ISequenceService sequenceService) 
     : base(sequenceService) 
    { 
     _product = productService; 
    } 
} 
+0

對不起。我不明白你的榜樣。我需要的是構建BaseConstructor和sequenceService。 – 2011-12-24 08:19:08

+0

@ Samantha2 - 答案更新了選項。 – Oded 2011-12-24 08:24:45

+0

看到你對DI的評論,但已經使用Unity進行依賴注入。我不能用Unity做這個嗎?我想知道Unity是如何工作的,因爲它已經建立了我的AccountController並將實例提供給它。如果我只是打電話給BaseController,該怎麼辦? Unity會不會自動捕獲並設置SequenceService? – 2011-12-24 08:25:04