问题
I'm updating my apps and now I use MVVMLight 5.3.0 the viewmodellocator crash at the line
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
I read that ih the latest version of MVVMLight, the class servicelocartor is removed, And the Microsoft.Practices.ServiceLocation was gone ...
So, what can/must i do for makes work the app again? Thanks
回答1:
From the blog post introducing the standard library version of MVVMLight, remove the line of code below:
// OLD ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
Whenever you use the ServiceLocator.Current use SimpleIoc.Default instead. For example
// OLD var nav = ServiceLocator.Current.GetInstance<INavigationService>();
// NEW
var nav = SimpleIoc.Default.GetInstance<INavigationService>();
http://www.mvvmlight.net/std10
回答2:
Always I use MVVMLight in such a way, without setting locator provider for ServiceLocator
. Typically, your view model locator should like this:
public class ViewModelLocator
{
public ViewModelLocator()
{
SimpleIoc.Default.Register<IDataProvider, SQLiteDataProvider>();
SimpleIoc.Default.Register<IDialogService, DialogService>();
SimpleIoc.Default.Register(GetNavigationService);
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<MessageViewModel>();
SimpleIoc.Default.Register<SearchViewModel>();
SimpleIoc.Default.Register<SettingViewModel>();
...
}
public MainViewModel MainViewModel => SimpleIoc.Default.GetInstance<MainViewModel>(Guid.NewGuid().ToString());
public MessageViewModel MessageViewModel => SimpleIoc.Default.GetInstance<MessageViewModel>(Guid.NewGuid().ToString());
public SearchViewModel SearchViewModel => SimpleIoc.Default.GetInstance<SearchViewModel>(Guid.NewGuid().ToString());
public SettingViewModel SettingViewModel => SimpleIoc.Default.GetInstance<SettingViewModel>(Guid.NewGuid().ToString());
...
public INavigationService GetNavigationService()
{
var navigationService = new NavigationService();
navigationService.Configure(Pages.MainView.ToString(), typeof(MainPage));
navigationService.Configure(Pages.MessageView.ToString(), typeof(MessagePage));
navigationService.Configure(Pages.SearchView.ToString(), typeof(SearchPage));
navigationService.Configure(Pages.SettingView.ToString(), typeof(SettingPage));
...
return navigationService;
}
}
来源:https://stackoverflow.com/questions/47486388/uwp-mvvmlight-replacing-obsolete-servicelocator