title: ASP.Net MVC 3 architecture with Web API business layer
body: <p>I’m in the process of writing my first MVC application, and whilst I have been trying to apply the guidelines given in other answers the structure of the project is making this difficult (and I'm making a mess of things!).
  Currently, the application is split into the following layers:</p>
  
  <ul>
  <li><p><strong>Domain objects/logic accessed using Web API services.</strong> I’m treating this layer as a black box as some of the code is used in several WPF applications and is not under my control. </p></li>
  <li><p><strong>Repository layer.</strong> This layer calls the Web API services, and was added to help unit testing. It calls the services and returns a deserialized domain model.</p></li>
  <li><p><strong>Controller.</strong>  I have two different styles of controller depending on how the data will be used.  </p>
  
  <p>In the first type, the controller calls the methods in the repository and then uses a mapper class to convert the domain objects to the view models. The mapping is done manually as some of the view models are significantly different to the underlying domain objects. E.g:</p>
  
  <pre><code>DomainObject domainObject = m_repository.GetObject(id);
  ViewModel model = ModelMapper.PopulateViewModel(domainObject);
  return View(model);
  </code></pre>
  
  <p>The second type is designed to provide data used by AJAX calls. Here, the controller calls the repository as before, but then the domain model is converted to JSON using custom Json.Net  converters. E.g:</p>
  
  <pre><code>var jsonNetResult = new JsonNetResult();
  DataObject data = m_repository.GetData(id);
  
  jsonNetResult.Converters.Add(new DataObjectConverter());
  jsonNetResult.Data = data;
  
  return jsonNetResult;
  </code></pre></li>
  </ul>
  
  <p><strong>Questions:</strong></p>
  
  <p>It feels like I’m doing a lot of switching between JSON, the domain objects and view models.  This doesn’t seem particularly performant – can/should the repository be creating the view models instead of the controller? </p>
  
  <p>If the data is intended to be supplied as JSON, I'm converting the domain objects to JSON and not using view models. This seems inconsistent, but I don't want to map to a view model just for the sake of it. Is this the right approach?</p>
  
  <p>I can find a lot of examples using MVC on top of the entity framework, but I’m struggling to find examples of using Web API within an MVC application. Can anyone point me in the right direction?</p>
  
  <p>Hopefully this makes sense, thanks!</p>