簡體   English   中英

使用Unity作為IoC的構造函數依賴項注入

[英]Constructor dependency injection using Unity as IoC

我有一個窗體,它在組合框中顯示三個項目。 大洲,國家和城市

如果選擇一個項目,例如,如果選擇“城市”,然后單擊“獲取結果”按鈕,則我將通過業務和數據層將選擇命令發送到數據庫,然后檢索“城市”類型的列表。

然后將列表綁定到UI表單上的網格。

這些類:洲,國家和城市使用屬性字符串“名稱”實現IEntities接口。

按鈕單擊事件使用以下方法調用業務層:

click(object sender, EventArgs e)
{
    string selectedItem = comboBox.SelectedItem;
    IEntities entity = null;
    List<IEntities> list = null;

    if (selectedItem == "Cities")
    {
        entity  = new Cities("City");   
    }

    if (selectedItem == "Continents")
    {
        entity  = new Continents("Continents");   
    }

    if (selectedItem == "Countries")
    {
        entity  = new Countries("Countries");   
    }

    //Then I call a method in Business Layer to return list
    BL bl = new BL(entity);
    list = bl.GetItems();
    myDataGrid.DataContext = list;//to bind grid to the list
}

業務層如下所示:

public class BL
{

    public IEntities _entity;

    //constructor sets the variable
    public BL(IEntity entity)
    {
        _entity = entity;
    }

    public IList<Entities> GetItems()
    {
        //call a method in data layer that communicates to the database
        DL dl = new DL();
        return dl.CreateItemsFromDatabase(_entity.Name);//name decides which method to call
    }
}

我想將Unity用作IOC,所以我不想在按鈕click事件中使用工廠(某種)模式(如果使用else則使用else並使用硬編碼的類名),而是要使用容器的配置來創建相關的類實例。 當IEntities實例傳遞給BL類的構造函數時,我想使用Unity傳遞對象。 您能建議如何做嗎?

確實存在,這種設計不太適合合並IoC容器。

只要你的ComboBox仍然包含字符串,你將不得不進行比較,對在硬編碼值switch語句或設置的if地方

此外, BL類采用IEntity類型的構造函數參數,但在運行時可以是許多不同類型中的任何一個對象。 無法在啟動時將Unity配置為實例化BL而又不告訴它用作該參數的內容(實際上沒有任何收獲)。

不過,有趣的是,您似乎是為了實例化這些Entity對象,其唯一目的是將其string名稱傳遞給CreateItemsFromDatabase方法。 您沒有將其類型用於任何東西。 看來,您可以完全跳過構造函數參數,只需將所選的stringComboBox直接傳遞到GetItems方法即可獲得相同的結果。 如果您還有其他原因,則至少不要在構造函數中提供名稱; 在每個類聲明constconst

可能更適合的是使GetItems為通用方法。 您可以將具體類型傳遞給方法,而不是將IEntity傳遞給BL構造函數:

var bl = new BL();
 var countries = bl.GetItems<Countries>();
 var cities = bl.GetItems<Cities>();
 var continents = bl.GetItems<Continents>();

暫無
暫無

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

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