【发布时间】:2015-01-20 10:56:03
【问题描述】:
我正在使用 MVVM Light。当我在我的资源中添加更多价值转换器时,我的应用程序崩溃并出现异常:
Microsoft.Practices.ServiceLocation.DLL 中出现“System.InvalidOperationException”类型的异常,但未在用户代码中处理
附加信息:必须设置 ServiceLocationProvider。
在App.xaml.cs OnLaunched 事件中我有这行
ServiceLocator.Current.GetInstance<MyViewModel>();
它在那里崩溃.. 在这个 ServiceLocator 中,我可以看到有一个 SetLocatorProvider 方法,它以 ServiceLocatorProvider 为参数。我在 Web 上找不到任何内容,并且 Microsoft 的 MSDN 页面已过时:
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
...
}
if (rootFrame.Content == null)
{
...
}
Window.Current.Activate();
DispatcherHelper.Initialize();
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
ServiceLocator.Current.GetInstance<MyViewModel>();
}
编辑:这是完整的 OnLaunched 事件。 放好后
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
发生异常:
在 GalaSoft.MvvmLight.Extras.DLL 中发生 Microsoft.Practices.ServiceLocation.ActivationException' 类型的异常,但未在用户代码中处理
附加信息:在缓存中找不到类型:cMC.ViewModel.MyViewModel。
这是 ViewModelLocator 的代码
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MyViewModel>();
}
public MyViewModel MyVM
{
get
{
return ServiceLocator.Current.GetInstance<MyViewModel>();
}
}
public static void Cleanup() {}
}
【问题讨论】:
-
由于 ServiceLocator 是诸如 unity 或 mef 等可用 IoC 容器的某种包装器...它需要您通过调用方法 ServiceLocator.SetLocatorProvider(() => new UnityServiceLocatorAdapter(容器));
标签: c# .net xaml windows-phone-8.1 mvvm-light