0

我在我的项目中使用MVVM Light,但我不确定如何在ViewModelLocator类中注册Viewmodel类,该类在构造函数中接受参数。如何注册一个具有依赖注入构造函数的类? (SimpleIoC)

我查看了docs on IoC,但没有看到与注册依赖项注入构造函数有关的任何事情,即需要一个参数。

在我要注册类,构造发生在它的列表的参数是这样的:

public ViewSubjectGradeViewModel(IEnumerable<ScoreModel> addedSubjectGradePairs) 

但是,当我执行naviagation到ViewModel类,我得到一个ActivationException,即细节:

“Microsoft.Practices.ServiceLocation.ActivationException是由用户代码未处理 的HResult = -2146233088 消息=无法注册:在ViewSubjectGradeViewModel找到多个构造,但标有PreferredConstructor无 源= GalaSoft.MvvmLight.Extras 堆栈跟踪: 在GalaSoft.MvvmLight.Ioc.SimpleIoc.GetPreferredConstructorInfo(IEnumerable`1 constructorInfos,类型resolveTo) 在GalaSoft.MvvmLight.Ioc.SimpleIoc.GetConstructorInfo(类型的serviceType) 在GalaSoft。 MvvmLight.Ioc.SimpleIoc.Register [TClass](布尔createInstanceImmediately) 在GalaSoft.MvvmLight.Ioc.SimpleIoc.RegisterTClass 在LC_Points.ViewModel.ViewModelLocator..ctor() 在LC_Points.LC_Points_WindowsPhone_XamlTypeInfo.XamlTypeInfoProvider.Activate_0_ViewModelLocator() 在LC_Points.LC_Points_WindowsPhone_XamlTypeInfo.XamlUserType.ActivateInstance() InnerException: “

有谁知道如何解决此错误并指定“PreferredConstructor?”

错误本身在哪里注册的ViewModel类行抛出:

enter image description here

这是虚拟机的注册是指我ViewModelLocator类:

namespace LC_Points.ViewModel 
{ 
    /// <summary> 
    /// This class contains static references to all the view models in the 
    /// application and provides an entry point for the bindings. 
    /// </summary> 
    public class ViewModelLocator 
    { 
     /// <summary> 
     /// Initializes a new instance of the ViewModelLocator class. 
     /// </summary> 
     public ViewModelLocator() 
     { 
      ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); 


      SimpleIoc.Default.Register<MainViewModel>(); 
      SimpleIoc.Default.Register<ScoreModel>(); 
      SimpleIoc.Default.Register<ViewSubjectGradeViewModel>(); 


     } 

     public MainViewModel MainPage 
     { 
      get 
      { 
       return ServiceLocator.Current.GetInstance<MainViewModel>(); 
      } 
     } 


     public ViewSubjectGradeViewModel ViewSubjectGradePage 
     { 
      get 
      { 
       return ServiceLocator.Current.GetInstance<ViewSubjectGradeViewModel>(); 
      } 
     } 


     public ScoreModel ScoreProperty 
     { 
      get 
      { 
       return ServiceLocator.Current.GetInstance<ScoreModel>(); 
      } 
     } 

    } 
} 

回答

4

你可以单独注册界面就像这样。 你必须注册实现它的接口:

class YourImplement: IEnumerable 
{ 
.... 
} 

SimpleIoc.Default.Register<IEnumerable, YourImplement>(); 

或者这样:

SimpleIoc.Default.Register<IEnumerable>(()=>new YourImplement()); 
+0

为了清楚起见,我刚刚编辑了我的上述问题,请不要完全理解您的解决方案。你可以看看吗?基本上我试图注册一个类的IEnumerable列表的构造函数有依赖。 –

2

布赖恩,这是你在找什么...

假设:

interface IMyInterface {...} 
class MyClass : IMyInterface {...} 
IEnumerable myEnumerable = new List<string>(); 

Then:

SimpleIoc.Default.Register<IMyInterface>(() => new MyClass(myEnumerable)); 
相关问题