0
votes

My goal was to load one of my data services before the rest of the application (visible UI).

My MVVMlight setup was pretty well stock, before trying to pre-load my data service.

  • The ViewModelLocator is initialized in the App.Xaml.
  • The ViewModels and DataServices are registered, and work fine.

In my App.xaml.cs the main view is loaded like so.

var mainWindow = new View.MainWindow();
mainWindow.Show();

To pre-load my data service I set my data service to createInstanceImmediately, then added the following just above the mainWindow code.

DataService dataService = SimpleIoc.Default.GetInstance<IDataService>();

That line generates an exception "CommonServiceLocator.ActivationException: 'Type not found in cache: Namespace.IDataService.'"

If move that line down below the mainWindow code, it works just fine.

My first thought was that it was a timing issue, but if I add a delay, I still get the error. So it appears that the application resource is not loading until after a view is loaded. I wouldn't not have thought that to be, since the app.xaml and the app.xaml.cs are really part of the same class. Regardless, I'm not sure how to get around this, or if I even can.

Why doesn't the ViewModelLocator load without a view? Is there a way to force it to load the application resource manually? Or is there a better way?

1
You need to move service registration before creating the window. It should be one of the first lines in your App class contructor - Krzysztof Skowronek

1 Answers

0
votes

I did finally find a solution.

The trick is to manually instantiate the ViewModelLocator from the application resources.

private ViewModelLocator viewModelLocator = App.Current.Resources["Locator"] as ViewModelLocator

The view models can then be accessed via viewModelLocator.Main (or whatever property name you assign) if needed.

Placement of this bit is important. It will not work from the App Constructor, but it does from the Application_Startup Event handler. I ended up putting in its own class that I load from Application_Startup, more to keep my App.xaml.cs clean than otherwise.

After using this for a little while, I am growing fond of it and may start using more often. It makes hooking up my events between view models quite easy, when my needs don't require the messenger service.