[英]Unity IoC : Create instance of an interface without constructor dependency injection
我是Unity和DI術語的新手,因此試圖理解它是如何工作的。 我有以下代碼使用Unity容器實現DI。
public class DashboardService: IDashboardService
{
private readonly IRepository<USERROLE> repoUserRole;
private readonly IRepository<INSTITUTION> repoInstitution;
public DashboardService(
IRepository<USERROLE> repoUserRole, IRepository<INSTITUTION> repoInstitution)
{
this.repoUserRole = repoUserRole;
this.repoInstitution = repoInstitution;
}
public List<USERROLE> GET(List<string> Id)
{
// Use repoUserRole object to get data from database
}
}
控制器正在調用此服務:
public class DashboardController : ApiController
{
private readonly IDashboardService dashboardService;
public DashboardController(IDashboardService dashboardService)
{
this.dashboardService = dashboardService;
this.mapper = mapper;
}
//Action method which uses dashboardService object
}
這是Unity配置:
var container = new UnityContainer();
container.RegisterType(typeof(IDashboardService), typeof(DashboardService))
.RegisterType(typeof(IRepository<>), typeof(Repository<>));
return container;
問題:
DashboardService
構造函數,我將獲得null存儲庫對象。 Unity
中存儲庫接口的依賴關系,為什么我在那里得到null? 如果我注釋掉DashboardService構造函數,我將獲得null存儲庫對象。
如果不向類添加構造函數,C#將在編譯期間為您生成公共無參數構造函數。 這會導致Unity調用'invisible'無參數構造函數,這就是為什么沒有私有字段被初始化的原因。
要防止出現這類意外編程錯誤,請始終確保在項目的屬性構建選項卡中啟用“將所有警告視為錯誤”。 這將確保編譯器停止編譯,因為它檢測到這些未初始化的字段。
有沒有辦法在不使用構造函數模式的情況下傳遞存儲庫依賴性?
是的,但是你可以使用的其他方法都會產生代碼氣味或反模式。 構造函數注入幾乎在所有情況下都是最佳解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.