MvvmLight ViewmodelLocator StaticResource stops loading

556 views Asked by At

I am consistently experiencing the weirdest thing whenever I use MVVM Light. I create a ViewModelLocator and register in as a static resource in app.xaml:

<viewmodel:WindowsViewModelLocator x:Key="ViewModelLocator" />

Everything works fine, meaning that on launch the static resource is registered, I can use it, and I can see it by going to

App.Current.Resources["ViewModelLocator"]

but then suddenly, randomly, and permanently, this stops working. It has happened to me on every single project, but I'm yet to identify why, as I can't identify the consistent action I did to make it stop working, nor can I figure out any way to revert it back to whatever it was I had when it was working...

the only way to move on is to manually register the resource on startup like this:

if (!Resources.ContainsKey("ViewModelLocator") || Resources["ViewModelLocator"] == null) Resources.Add("ViewModelLocator", new WindowsViewModelLocator());

and finally everything starts working again and usually that's the end of it.

But it happens EVERY SINGLE TIME.

I set a breakpoint in the constructor of the locator and it surely is not being hit... anybody have any idea what I might have possibly done wrong?

EDIT: I finally found the actual exception which was:

A first chance exception of type 'Microsoft.Practices.ServiceLocation.ActivationException' occurred in GalaSoft.MvvmLight.Extras.DLL

which led me to find the answer which I've posted below. thanks!

1

There are 1 answers

0
SelAromDotNet On BEST ANSWER

It turns out the problem was the order in which I was registering the viewmodels that have dependencies. I have a base ViewModelLocator that initialized the ViewModels, and an inherited ViewModelLocator that contains the Platform-specific code...

In one of the constructors of one of the ViewModels, I was referencing one of the dependent types, which would be registered with a design-time instance. But since this was runtime (which doesn't get registered until it hits the derived platform viewmodellocator) the reference was null.

I moved the dependent code out of the constructor into a more appropriate location and that appears to fix it!

long story short: if you're having this issue, make sure you are initializing everything correctly in the right order and in the right place!