【问题标题】:ServiceLocationProvider is null when launched as a Share TargetServiceLocationProvider 在作为共享目标启动时为空
【发布时间】:2025-12-11 08:10:01
【问题描述】:

我正在使用 MVVM Light,一切都很好,除了将我的 Windows Phone 8.1 WinRT 应用程序作为共享目标启动。

当我尝试分配 MainViewModel viewModel = ServiceLocator.Current.GetInstance<MainViewModel>(); 时,ServiceLocator.Current 出现异常。

异常消息:必须设置 ServiceLocationProvider。

我是否需要在 App.xaml.cs OnShareTargetActivated 事件中做一些额外的事情来确保定位器正在运行?

更新: 需要将 ShareTarget 页面视为您的应用程序的一个小扩展。似乎并非所有应用程序的资源都已加载(包括 App.xaml 中的应用程序范围的资源)。所以我只是在共享页面的构造函数中创建了一个新的 MainViewModel 实例,只加载了完成共享所需的内容,保存信息并调用ShareOperation.ReportCompleted。这会将用户返回到正在共享的应用程序。

我仍然没有找到在我的 ViewModel 中获取其他资源的好解决方案,但目前可行。

【问题讨论】:

    标签: windows-runtime winrt-xaml windows-phone-8.1 mvvm-light


    【解决方案1】:

    这表明以下行没有被执行:

    ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
    

    此行将指示 ServiceLocator 类使用 SimpleIoc.Default 实例作为其 ServiceLocator.Current。当您将应用程序作为共享目标运行时,初始化会略有不同,并且可能 ViewModelLocator 没有被初始化。在使用 ServiceLocator 之前,您需要找到一个好的位置来执行初始化。

    干杯 洛朗

    【讨论】:

    • Laurent,我发现 App.xaml 中设置的 ViewModelLocator 在其他场景中也没有实例化。如果我只是在 OnActivated 中新建一个 ViewModelLocator 会发生什么情况,我会获得 MainViewModel 的多个实例,还是 IOC 会保持同一个实例