[英]c# class inherits from base class with constructor with dependency injection
[英]Why set up a constructor in a class to set a base parameter when I could do the same in a class it inherits from?
我有以下代碼:
public abstract class ApiBaseController : ApiController
{
protected IUow Uow { get; set; }
}
和:
public class ContentStatusController : ApiBaseController
{
public ContentStatusController(IUow uow)
{
Uow = uow;
}
}
有什么原因導致我無法在ApiBaseController中編寫Uow的分配代碼(使用IOC)?
我問的原因是因為我試圖做與Code Camper應用程序示例類似的事情,並且我注意到在該示例中,工作單元分配始終在控制器本身的構造器中執行,而不是在ApiBaseConstructor中執行。 在示例中,我看到這是構造函數中唯一要做的事情。
如果我在基本控制器中進行分配,那么我該如何編寫代碼,並且Uow仍需要對其進行“保護”,才能在繼承自ApiBaseController的控制器中使用它?
您的IOC容器正在通過構造函數注入依賴項。 如果您想繼續使用該機制(某些容器允許例如屬性注入,但並非每個人都喜歡這樣做),則仍需要在派生類中具有相同的構造函數,以將注入的組件傳遞給基類1 。
就像是:
public abstract class ApiBaseController : ApiController
{
public ApiBaseController(IUow uow)
{
Uow = uow;
}
protected IUow Uow { get; private set; }
}
public class ContentStatusController : ApiBaseController
{
public ContentStatusController(IUow uow) : base(uow) //<-- This is needed
{
}
}
1因為類不繼承構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.