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:
Domain objects/logic accessed using Web API services. 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.
Repository layer. This layer calls the Web API services, and was added to help unit testing. It calls the services and returns a deserialized domain model.
Controller. I have two different styles of controller depending on how the data will be used.
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:
DomainObject domainObject = m_repository.GetObject(id); ViewModel model = ModelMapper.PopulateViewModel(domainObject); return View(model);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:
var jsonNetResult = new JsonNetResult(); DataObject data = m_repository.GetData(id); jsonNetResult.Converters.Add(new DataObjectConverter()); jsonNetResult.Data = data; return jsonNetResult;
Questions:
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?
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?
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?
Hopefully this makes sense, thanks!