0

我正在开发一个 Xamarin Forms 应用程序,Windows Phone 的构建和运行一切顺利。但是,当我尝试运行 Android 版本时,它构建正常然后失败,并且在调用 ServiceLocator 以解析 ViewModelLocator 中的 ViewModel 时出现异常。

ViewModelLocator 中的行中断

return ServiceLocator.Current.GetInstance<MainViewModel>();

System.Reflection.TargetInvocationException
Source  "mscorlib"  string
StackTrace  "at System.Reflection.MonoMethod.Invoke (object,System.Reflection.BindingFlags,System.Reflection.Bind…"

并将鼠标悬停在“GetInstance”节目上

Could not resolve type: global::Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<global::hms.BillSplitter.ViewModel.PCL.MainViewModel>

我的 ViewModel 唯一的构造函数看起来像

public MainViewModel(INavigationService navigationService, ICountryTippingService countryTippingService, AppSettings appSettings)
{
    _navigationService = navigationService;
    _countryTippingService = countryTippingService;
    ThisAppSettings = appSettings;
    ThisBillDetail = new BillDetail();
    ThisBillDetail.TotalOnBill = 0;
}

所有依赖项都在此之前注册,ViewModelLocator例如

SimpleIoc.Default.Register(() => new HmsPublicCoreMobileServiceClient(HmsCommonSettingConstants.HmsPublicCoreServiceUrl, HmsCommonSettingConstants.HmsPublicCoreServiceAppKey));
var prefService = ServiceLocator.Current.GetInstance<IPreferenceService>();
SimpleIoc.Default.Register(() => (SettingsHelper.GetCurrentSettings(prefService)));

SimpleIoc.Default.Register<MainViewModel>();

以及 MainActivity.cs (Android) 和 AppDelegate(iOS) 中的一些平台特定的,例如

SimpleIoc.Default.Register(() => new PreferenceService(this));

我不明白的是它在 Windows Phone 中运行良好吗?Android有什么不同?有人在 Xamarin 1.3+ 中使用过 SimpleIoc 吗?

我应该使用工厂来创建他的 ViewModel 吗?

任何帮助都会非常好,非常感谢。我正在使用 MVVMLight (5.1.0.1) 和 Xamarin (1.3.3) 的所有最新版本。

4

1 回答 1

1

我终于弄清楚了问题所在,它非常基本,与 MvvmLight 和/或 Xamarin Forms 更新无关!

我犯了在工厂中注册具体类的错误,然后尝试在接口上获取实例。SimpleIoC 无法调和它。

从上面的代码

SimpleIoc.Default.Register(() => (SettingsHelper.GetCurrentSettings(prefService)));

本来应该

SimpleIoc.Default.Register<IPreferenceService>(() => (SettingsHelper.GetCurrentSettings(prefService)));

这样线

var prefService = ServiceLocator.Current.GetInstance<IPreferenceService>();

会知道我在说什么。

无论如何,如果你遇到这样的错误,你就会知道要寻找什么!!

于 2015-02-13T15:55:41.087 回答