title: ASP.NET MVC Design Pattern Best Practice with Services
body: <p>I have an ASP.NET MVC 3 application.</p>
  
  <p>I have a <code>Model</code>, <code>ViewModel</code>, <code>View</code>, <code>Controller</code>.</p>
  
  <p>I use <code>Ninject</code> as IoC.</p>
  
  <p>My <code>Controller</code> uses a <code>ViewModel</code> to pass data to the <code>View</code>.</p>
  
  <p>I've started to use <code>Service</code>s (concrete and interface types) to take information from the <code>ViewModel</code> and query it against the database to manipulate it.</p>
  
  <p>Can I use the same <code>Service</code> to setup the <code>ViewModel</code>? Or is this going against the grain of the design pattern?</p>
  
  <p>I.e. Can I abstract setting up the <code>ViewModel</code> in the <code>Service</code> layer?</p>
  
  <p><em><strong>Scenario</em></strong></p>
  
  <p>The scenario is; my <code>Model</code> has lots of references to other <code>Models</code>, so when I setup the <code>ViewModel</code> in the controller it's to verbose, and I feel the <code>Controller</code> is doing too much. So I want to be able to just do something like:</p>
  
  <p><code>var vm = _serviceProvider.SetupViewModel(Guid model1Id, Guid model2Id, /*etc..*/)</code></p>
  
  <p>And the <code>SetupViewModel</code> function in the <code>ServiceProvider</code> would look like this:</p>
  
  <pre><code>public MyModelViewModel SetupViewModel(Guid model1Id, Guid model2Id, /*etc...*/)
  {
      var vm = new MyModelViewModel();
      var model1 = _repository.Model1s.FirstOrDefault(x =&gt; x.Id.Equals(model1Id));
      var model2 = _repository.Model2s.FirstOrDefault(x =&gt; x.Id.Equals(model2Id));
  // etc....
  
      vm.Model1 = model1;
      vm.Model2 = model2;
  
      return vm;
  }
  </code></pre>
  
  <p>By doing this I could also add some <code>null</code> conditions as well, not worrying about making my <code>Controller</code> really really really big!!</p>
  
  <p>I use 1 <code>ViewModel</code> for the Create/Edit actions. I don't reuse the <code>ViewModel</code> elsewhere.</p>