title: Caliburn.Micro + Unity 2.1 + MVVM: example code
body: <p>I'm trying to implement Unity in a WPF MVVM application, but I'm missing the big picture.</p>
  
  <p>At this moment I have created a bootstrapper like this:</p>
  
  <pre><code>  public class MainBootstrapper : Bootstrapper&lt;MainViewModel&gt;
    {
      private UnityContainer container;
  
      protected override void Configure()
      {
        container = new UnityContainer();
        container.RegisterType&lt;IServiceLocator, UnityServiceLocator&gt;(new ContainerControlledLifetimeManager());
        container.RegisterType&lt;IWindowManager, WindowManager&gt;(new ContainerControlledLifetimeManager());
        container.RegisterType&lt;IEventAggregator, EventAggregator&gt;(new ContainerControlledLifetimeManager());
      }
  
      protected override object GetInstance(Type service, string key)
      {
        if (service != null)
        {
          return container.Resolve(service);
        }
  
        if (!string.IsNullOrWhiteSpace(key))
        {
          return container.Resolve(Type.GetType(key));
        }
  
        return null;
      }
  
      protected override IEnumerable&lt;object&gt; GetAllInstances(Type service)
      {
        return container.ResolveAll(service);
      }
  
      protected override void BuildUp(object instance)
      {
        container.BuildUp(instance);
      }
    }
  </code></pre>
  
  <p>How what is the best way to use this?
  This code currently works:</p>
  
  <pre><code>  public class MainViewModel : PropertyChangedBase
    {
      public MainViewModel()
      { }
  
      [Dependency]
      public Sub1ViewModel Sub1VM { get; set; }
      [Dependency]
      public Sub2ViewModel Sub2VM { get; set; }
    }
  </code></pre>
  
  <p>the MainView has this:</p>
  
  <pre><code>&lt;Grid&gt;
      &lt;Grid.RowDefinitions&gt;
          &lt;RowDefinition Height="*" /&gt;
          &lt;RowDefinition Height="*" /&gt;
      &lt;/Grid.RowDefinitions&gt;
  
      &lt;ContentControl Grid.Row="0" Name="Sub1VM" /&gt;
      &lt;ContentControl Grid.Row="1" Name="Sub2VM" /&gt;
  
  &lt;/Grid&gt;
  </code></pre>
  
  <p>First of all: the code that I shared, is this the correct way of using Unity + Caliburn?</p>
  
  <p>Now let's say that my Sub1VM uses a model 'M1', but Sub2VM needs to use the same model to display information but not by making another instance of model M1. (singleton)</p>
  
  <p>How does this work now? Show I use a IServiceLocator in each viewmodel constructor? Could somebody share a code sample to explain it?</p>