【问题标题】:mvvm light simpleIoc constructor injectionmvvm light simpleIoc 构造函数注入
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 它可以工作,但这不会破坏依赖注入的目的,我如何在其接口上注册一个类型?谢谢
  • 您不会将通用列表映射到特定类型。这是没有意义的,因为您希望能够对许多不同类型使用通用列表。您可以映射视图模型界面,例如IShowViewModel,虽然针对具体的视图模型类型,但那是另一回事了,因为您的 ShowEmployeeViewModel 类甚至没有实现接口,所以在这里不适用。
猜你喜欢
  • 2015-04-04
  • 2014-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
相关资源
最近更新 更多