title: Merged ResourceDictionary initalization in UWP app
body: <p>During development of my UWP app I have noticed and intersting oddity which I have hard time explaining.</p>
  
  <p>I user MvvmLight and I decided to add the ViewModelLocator resource instance in a separate ResourceDictionary <em>Core.xaml</em> which will be referenced from <code>MergedDictionaries</code> in <em>App.xaml</em>.
  Following is the content of <em>App.xaml</em>:</p>
  
  <pre><code>&lt;Application ...&gt;
  &lt;Application.Resources&gt;
      &lt;ResourceDictionary&gt;
          &lt;ResourceDictionary.MergedDictionaries&gt;
              &lt;ResourceDictionary Source="Resources/Core.xaml" /&gt;
              &lt;ResourceDictionary Source="Resources/Converters.xaml" /&gt;
          &lt;/ResourceDictionary.MergedDictionaries&gt;
      &lt;/ResourceDictionary&gt;
  &lt;/Application.Resources&gt;
  &lt;/Application&gt;
  </code></pre>
  
  <p>Contents of <em>Core.xaml</em>:</p>
  
  <pre><code>&lt;ResourceDictionary ...&gt;
      &lt;viewModel:ViewModelLocator x:Key="Locator" /&gt;
  &lt;/ResourceDictionary&gt;
  </code></pre>
  
  <p>Now I supposed the resources in <em>Core.xaml</em> are initialized during the <code>InitializeComponent</code> method call in <em>App.xaml.cs</em>, but when I tried to use the <code>ServiceLocator</code> class (which is set in the constructor of ViewModelLocator in MvvmLight) - like this - <code>ServiceLocator.Current.GetInstance&lt;INavigationService&gt;().Navigate&lt;MainViewModel&gt;();</code> - I get an exception saying:</p>
  
  <pre><code>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.
  </code></pre>
  
  <p>Indeed, if I put an breakpoint in the constructor of ViewModelLocator, it is not called before the Window is activated. More interestingly still - if I manually reference the <em>Locator</em> resource key (for example putting <code>Debug.WriteLine(Resources["Locator"]);</code> above the call of <code>ServiceLocator</code>), everything works fine. The same goes if I move the <code>ViewModelLocator</code> resource directly to App.xaml - then it is instantiated during <code>IntializeComponent</code>.</p>
  
  <p>Is there a lazy instantiation of merged resource dictionaries in UWP apps? Or why does it behave this way?</p>