![](/img/trans.png)
[英]Unity IoC : Create instance of an interface without constructor dependency injection
[英]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
方法。 您没有将其类型用于任何东西。 看来,您可以完全跳过构造函数参数,只需将所选的string
从ComboBox
直接传递到GetItems
方法即可获得相同的结果。 如果您还有其他原因,则至少不要在构造函数中提供名称; 在每个类声明const
其const
。
可能更适合的是使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.