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>(); 

會知道我在說什麼。

無論如何,如果你得到這樣的錯誤,你會知道該找什麼!

相關問題