【发布时间】:2017-02-20 04:33:30
【问题描述】:
我想用 ServiceLocator 向我的视图模型构造函数注入一个列表
我的视图模型:
public class ShowEmployeeViewModel: ViewModelBase
{
private IList<IEmployee> _empl;
public ShowEmployeeViewModel(IList<IEmployee> emp)
{
this._empl = emp;
_empl.Add(new Employee() { empName = "foo", enpFunction = "bar" });
}
}
我的服务定位器:
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
//register the interface against the class
SimpleIoc.Default.Register < IList < IEmployee >, List <Employee>>();
SimpleIoc.Default.Register<ShowEmployeeViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public ShowEmployeeViewModel ShowEmployee
{
get
{
return ServiceLocator.Current.GetInstance<ShowEmployeeViewModel>();
}
}
当我运行此代码时出现错误: “无法注册:在 List`1 中找到多个构造函数,但没有一个用 PreferredConstructor 标记。” PS:我只在尝试注册列表“IList”时出现此错误,但是当我像这样注册我的界面时:
SimpleIoc.Default.Register < IEmployee , Employee >();
它工作正常,知道如何注册列表吗? 提前致谢
【问题讨论】:
-
你把事情搞混了。 DI 容器(以及一般的 DI)并不意味着构建 DTO 和实体;它旨在构建应用程序组件的图表,即包含该应用程序行为的类。
ShowEmployeeViewModel是一个 DTO,IEmployee是一个实体。不要在你的容器中注册它们。
标签: c# dependency-injection mvvm-light simpleioc