UWP / MVVMlight : Replacing Obsolete ServiceLocator

主宰稳场 提交于 2020-03-04 23:00:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!