簡體   English   中英

Unity IoC:創建沒有構造函數依賴注入的接口實例

[英]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;

問題:

  1. 截至目前,我的代碼工作正常,但如果我注釋掉DashboardService構造函數,我將獲得null存儲庫對象。
  2. 我正在解析Unity中存儲庫接口的依賴關系,為什么我在那里得到null?
  3. 有沒有辦法在不使用構造函數模式的情況下傳遞存儲庫依賴性?

如果我注釋掉DashboardService構造函數,我將獲得null存儲庫對象。

如果不向類添加構造函數,C#將在編譯期間為您生成公共無參數構造函數。 這會導致Unity調用'invisible'無參數構造函數,這就是為什么沒有私有字段被初始化的原因。

要防止出現這類意外編程錯誤,請始終確保在項目的屬性構建選項卡中啟用“將所有警告視為錯誤”。 這將確保編譯器停止編譯,因為它檢測到這些未初始化的字段。

有沒有辦法在不使用構造函數模式的情況下傳遞存儲庫依賴性?

是的,但是你可以使用的其他方法都會產生代碼氣味或反模式。 構造函數注入幾乎在所有情況下都是最佳解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM