【问题标题】:Constructor dependency injection using Unity as IoC使用 Unity 作为 IoC 的构造函数依赖注入
【发布时间】:2010-12-29 01:06:57
【问题描述】:

我有一个表单,它在一个组合框中显示三个项目。 大陆、国家和城市

如果我选择一个项目,例如如果我选择城市,然后如果我点击“获取结果”按钮,我会通过业务和数据层向数据库发送一个选择命令,然后检索类型城市的列表。

然后列表绑定到 UI 表单上的网格。

类:Continents、Countrys 和 Cities 使用属性字符串“Name”实现 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,因此我不想在按钮单击事件中使用工厂(某种)模式以及 if then elses 并使用硬编码的类名,而是使用容器的配置来创建相关的类实例。而当 IEntities 实例传递给 BL 类的构造函数时,我想使用 Unity 传递对象。可以请教一下怎么做吗?

【问题讨论】:

    标签: c# wpf unity-container


    【解决方案1】:

    由于它存在,这种设计不太适合合并 IoC 容器。

    只要您的ComboBox 仍然包含字符串,您就必须将其与switch 语句或if 块集合中的硬编码值进行比较某处。 p>

    此外,BL 类采用 IEntity 类型的构造函数参数,但它可以是运行时许多不同类型中的任何一个对象。没有办法在启动时配置 Unity 以实例化 BL 而不告诉它使用什么作为该参数(实际上并没有任何好处)。

    不过,有趣的是,您似乎只是为了将它们的string 名称传递给CreateItemsFromDatabase 方法而实例化这些实体对象;您没有将其类型用于任何事情。似乎您可以完全跳过构造函数参数,只需将选定的stringComboBox 直接传递给GetItems 方法并获得相同的结果。如果您有其他原因这样做,您至少不应该在构造函数中提供名称;在每个类声明中将其设为const

    可能更适合的是使GetItems 成为通用方法。您可以将具体类型传递给方法,而不是将 IEntity 传递给 BL 构造函数:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多