我在我的項目中使用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類行拋出:
這是虛擬機的註冊是指我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>();
}
}
}
}
爲了清楚起見,我剛剛編輯了我的上述問題,請不要完全理解您的解決方案。你可以看看嗎?基本上我試圖註冊一個類的IEnumerable列表的構造函數有依賴。 –