mvvm light simpleIoc 构造函数注入

mvvm light simpleIoc constructor injection

我想使用 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>();
        }
    }

当我 运行 这段代码出现错误时: "Cannot register: Multiple constructors found in List`1 but none marked with PreferredConstructor." PS:我只在尝试注册列表时遇到此错误 "IList" 但是当我像这样注册我的界面时:

SimpleIoc.Default.Register < IEmployee , Employee >();

它工作正常,知道如何注册列表吗? 提前致谢

不要映射 IList 接口,为您的 ShowEmployeeViewModel 使用工厂 class:

SimpleIoc.Default.Register(() => new ShowEmployeeViewModel(new List<IEmployee>()));