ServiceLocationProvider must be set

v.g. picture v.g. · Jan 20, 2015 · Viewed 32.5k times · Source

I am using MVVM Light. When I add more value converters in my resources my app crashes with exception:

An exception of type 'System.InvalidOperationException' occurred in Microsoft.Practices.ServiceLocation.DLL but was not handled in user code

Additional information: ServiceLocationProvider must be set.

In the App.xaml.cs OnLaunched event I have this line

ServiceLocator.Current.GetInstance<MyViewModel>();

It crashes there.. In this ServiceLocator I can see there is a SetLocatorProvider method which takes as an argument ServiceLocatorProvider. I couldnt find anything in the Web and Microsofts MSDN page is dated:

protected override async void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;

        if (rootFrame == null)
        {
            ...
        }

        if (rootFrame.Content == null)
        {
            ...
        }

        Window.Current.Activate();

        DispatcherHelper.Initialize();

        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        ServiceLocator.Current.GetInstance<MyViewModel>();
    }

EDIT: Here is the full OnLaunched event. After putting

ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

an exception occures:

An exception of type Microsoft.Practices.ServiceLocation.ActivationException' occurred in GalaSoft.MvvmLight.Extras.DLL but was not handled in user code

Additional information: Type not found in cache: cMC.ViewModel.MyViewModel.

This is the code of ViewModelLocator

public class ViewModelLocator
{
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        SimpleIoc.Default.Register<MyViewModel>();
    }

    public MyViewModel MyVM
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MyViewModel>();
        }
    }

    public static void Cleanup() {}
}

Answer

v.g. picture v.g. · Jan 20, 2015

I kinda figured it out.

There was also a need to register the ViewModel, something that happened in the ViewModelLocator constructor, but for some reason the constructor is executed later. So I modified the ViewModelLocator class like this:

public class ViewModelLocator
{
    public ViewModelLocator()
    {

    }

    public static void SetAndReg()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        SimpleIoc.Default.Register<MyViewModel>();
    }

    public MyViewModel MyVM
    {
        get
        {
            return ServiceLocator.Current.GetInstance<MyViewModel>();
        }
    }

    public static void Cleanup() {}
}

}

Then in the App.xaml.cs:

...OnLaunched(...)
{
...
        DispatcherHelper.Initialize();

        ViewModelLocator.SetAndReg();

        ServiceLocator.Current.GetInstance<MyViewModel>();
...
}