title: Injecting Commands into ViewModels
body: <p>I'm trying to figure out what is the right way to inject an <code>ICommand</code> into my ViewModel.  </p>
  
  <p>Given that my ViewModel looks like this.</p>
  
  <pre><code>public class ViewModel : IViewModel
  {
      ICommand LoadCommand { get; }
      ICommand SaveCommand { get; }
  }
  </code></pre>
  
  <p>I currently do this in my constructor</p>
  
  <pre><code>public ViewModel(IRepository repository, IErrorLog errorLog, IValidator validator)
  {
      LoadCommand = new LoadCommandImpl(repository, errorLog);
      SaveCommand = new SaveCommandImpl(repository, errorLog, validator);
  }
  </code></pre>
  
  <p>Note that the parameters are not used by the ViewModel at all, aside from constructing the commands.</p>
  
  <p>While I try to contain as much of the logic as possible in the injected interfaces, there is still logic in the commands.</p>
  
  <p>It would seem more appropriate to do this</p>
  
  <pre><code>public ViewModel(ICommand loadCommand, ICommand saveCommand)
  {
      LoadCommand = loadCommand;
      SaveCommand = saveCommand;
  
      LoadCommand.SetViewModel(this);
      SaveCommand.SetViewModel(this);
  }
  </code></pre>
  
  <p>However to do this, I would need to make my Unity registrations like this.  Which isn't the end of the world, but it seems like a pain.</p>
  
  <pre><code>container.RegisterType&lt;ICommand, LoadCommandImpl&gt;("loadCommand");
  container.RegisterType&lt;ICommand, SaveCommandImpl&gt;("saveCommand");
  
  container.RegisterType&lt;IViewModel, ViewModel&gt;(
      new InjectionConstructor(
          new ResolvedParameter&lt;ICommand&gt;("loadCommand"),
          new ResolvedParameter&lt;ICommand&gt;("SaveCommand")));
  </code></pre>
  
  <p>Alternatively, I could make <code>ILoadCommand</code> and <code>ISaveCommand</code> interfaces, but these interfaces would be empty or might implement <code>ICommand</code>.</p>
  
  <p>I'm not a huge fan of any of these solutions.  What is the recommended approach here?</p>
  
  <p><strong>Edit in response to blindmeis</strong></p>
  
  <p>Let's pretend this is something other than commands for a moment.</p>
  
  <pre><code>public ViewModel(IFoo foo)
  {
      Bar = new Bar(foo);
  }
  </code></pre>
  
  <p>In my opinion, it would be more appropriate to just inject IBar</p>
  
  <pre><code>public ViewModel(IBar bar)
  {
      Bar = bar;
  }
  </code></pre>
  
  <p>But now I have <code>Bar1</code> and <code>Bar2</code>.  So I can either do</p>
  
  <pre><code>public ViewModel(IFoo foo)
  {
      Bar1 = new Bar1(foo);
      Bar2 = new Bar2(foo);
  }
  </code></pre>
  
  <p>or</p>
  
  <pre><code>public ViewModel(IBar bar1, IBar bar2)
  {
      Bar1 = bar1;
      Bar2 = bar2;
  }
  </code></pre>