0

我正在开发一个Xamarin Forms应用程序,并且Windows Phone的构建和运行都很顺利。但是,当我尝试运行Android版本时,它会生成OK,然后失败,并在调用ServiceLocator来解析ViewModelLocator中的ViewModel时出现异常。在行MvvmLight的SimpleIoc打破Xamarin Forms 1.3 Android和iOS应用,但不是Windows Phone

打破了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> 

我的视图模型的唯一的构造看起来像

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)的所有最新版本。

+0

你能否也请显示注册? – 2015-02-11 15:31:35

+0

@DanielMay我在注册时添加了一些细节,这是非常标准的。不过它适用于Windows Phone,因此它在那里工作。 – NER1808 2015-02-12 18:52:55

回答

1

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

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

从上面的代码

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

应该已经

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

使该行

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

会知道我在说什么。

无论如何,如果你得到这样的错误,你会知道该找什么!

相关问题