title: WPF, MVVM IoC: Alternative to Service Locator Pattern. Need dependency in View code behind
body: <p>Following several guides I have a application layout like below using WPF .NET 4.7.1 and MVVM-Light. I'm totally new to WPF btw.</p>
  
  <p>App.xaml:</p>
  
  <pre><code>&lt;Application x:Class="My.App" 
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:viewmodel="clr-namespace:My.ViewModel" 
           StartupUri="View\MainView.xaml"&gt;
  &lt;Application.Resources&gt;
      &lt;ResourceDictionary&gt;
          &lt;viewmodel:ViewModelLocator x:Key="Locator" /&gt;
      &lt;/ResourceDictionary&gt;
  &lt;/Application.Resources&gt;
  </code></pre>
  
  <p></p>
  
  <p>That registers the "ViewModelLocator" class as a resources and sets the WPF startup to "View/MainView.xaml".</p>
  
  <p>MainView.xaml:</p>
  
  <pre><code>&lt;Window x:Class="My.View.MainView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt;
  
  &lt;Window.DataContext&gt;
      &lt;Binding  Path="Main" Source="{StaticResource Locator}"/&gt;
  &lt;/Window.DataContext&gt;
  </code></pre>
  
  <p></p>
  
  <p>Where the ViewModelLocator is used like a Service Locator Pattern. Here setting the DataContext to my "MainViewModel" (not shown). As much as I do not like this, I can live with it in the WPF XAML context. However now it turns out that I need a dependency in the code-behind of the view (not the ViewModel).</p>
  
  <p>MainView.cs:</p>
  
  <pre><code>public partial class MainView : INotifyPropertyChanged
  {
     public MainView()
     {
         // Need to access dependency here.          
     }
  }
  </code></pre>
  
  <p>Now I could just call the ViewModelLocator directly in that constructor and have that resolve from my IoC container - but then I've completely given in and accepting that pattern.</p>
  
  <p>I would prefer to have the dependency injected in the ctor of course, and if that is possible, I would also leave the ViewModelLocator entirely and inject the ViewModel here. </p>
  
  <p>So question is, are there some standard way of instructing WPF application to use my container? And if yes, is it adviceable to go down that path and not use the ViewModelLocator thing?</p>