FYI, I'm working on my first MVC web application using MVC 3 and Razor with C#, and .NET3.5/4.0, and I'm looking for the "best pratice" approach for using existing web services in an MVC 3 application. From what I have figured out so far it looks like all I need to do is the following. Include a reference to the existing web service in the MVC project, create a Model for the data I desire to use in the application, create a Controller that makes the web service call that then fills an object created from the Model (reading about AutoMapper to see how this helps in that process), and then create a View to display the data that was translated into the MVC view model.
The part that I'm having questions about is what is the best way to retrieve and create/update the data from the web service. Maybe I'm over complicating this but it seems like I'm missing something.
Do I need to create a "Domain Model" that maps to the data retrieved from the web service and then create "View Models" that map to the domain model, and then use the View Models within the MVC 3 application?
Basically I'm looking for input on how best to use existing web services as my data access layer.
On your data access layer you would open the connection, get the raw data and then close it. Identically to how you would get data from your database. You would then convert this raw data to your business layer (domain model) via a data adapter. Then any top level applications, such as your MVC3 website, will convert this domain model into an approriate view model, along with any other data for rendering, again through a data adapter.
The main argument for doing it this way is that the service is now accessible to any top tier application that requires it. It is also makes logical sense to put any sort of data retrieval methods in your data access layer, since that's logically what the data access layer is designed to do.
There is always the temptation to simply access the service from your controller, but separation of concerns might suggest this is a bad way to structure your code. You should encapsulate the service as a domain/business layer service for your applications.
So in short, you don't need to, but best practice suggests you should. It can feel tedious sometimes when there is little or no conversion between layers, but it often helps to stay consistent.
To obey the MVC pattern and its separation of concerns, calling the database must be in the model. And if this web services calls the database somehow, it should be at the Model level.
let the UI talk to the model directly, in case later u needed a webservice to integrate with another system you can create a service which calls that model
And you may want to cache it if its read-only
Related
I have a mvc web application which consumes web api service. If I want send complex form data represented in MyModel from mvc to the webservice, should webservice have MyModel as part of the project.
This way I would have MyModel on both projects, mvc and web service. Is this right approach?
In my opinion they should have different models and do the necessary mapping to avoid interdependent. In this case both projects ended up intact. This approach is called Data transfer object (DTO).
Benefits
You only care what you need thru mapping
No be big effect if model in different project change
Obviously you will not be tied up on other model outside of your domain
Disadvantages
You will end up many models
Expensive process
You will appreciate DTO specially if you're working in different teams working on different parts ex. One team woking on views and different team for backend. Also if your consuming external APIs. But you can apply this approach in your case.
After reading many articles about this i'm still not really sure what's the best solution could look like
Some telling me the ViewModel and the Model should get access to Database other are telling me only the Model should get access.
Further more does this also really depends on the way i connect to my database?
if i use a Repository should really both get access to it and
what if i want to use a EF should now only the "Model" are able to perform Database interactions?
Or does anybody know's a general rule about who should when are able to get access to the Database?
You should devide your application in Layers
UI layer - Responsible for the graphic part of your application containing your Views and ViewModels.
BusinessLayer - This is the layer your UI layer speaks with. Containing all logic and and it functions as gateway to your database. This contains your model and domain model.
Database layer - This layer is responsible for all communication to your database, generally providing generic methods for your Business layer to access and persist your data.
You should keep a clear seggregation between your UI and data.
There are offcourse many variations on this setup.
Currently I'm working on a project which is using WCF directly to interact with Service functionality instead of WCF RIA. The problem is I create Model for each Entity (in service) inside silverlight client application for validation, That's OK. But I should populate Server Entities with Client Models each time I want to Insert or Update an Entity in database. Is there any way to prevent these extra works?
A typical first version of an MVVM (Silverlight) Client and (WCF) Service has a lot of duplicate types, logic and mapping between types.
This is one of the reasons why WCF RIA Services has been created.
In a first version of an MVVM application the Model and ViewModel will be very similar. When new requirements appear and the Views get more and more functionality added these will diverge and the Model will become very different from the ViewModel.
The Model will be determined by the the service and the ViewModel by the Views. This will cause the mapping to be less and less trivial.
I have used T4 templates to generate ViewModels based on XML definitions. This prevented the need to write the boring, repetitive mapping code.
EDIT
See the MVMMapper project on Codeplex for the generation of ViewModels using T4
I am going to create a new asp.net web service (.NET framework 2.0), the functionality of the web service is to recieve xml input, perform the relevant operation (add/modify/delete) based on the input and return codes which indicates the status of the operation. I am planning to implement two layer architecture (Business layer and database layer) for this web service, could anyone advise whether this is the right structure or any other structure would perform well than this. Basically I need some inputs on designing the web service.
Thanks in advance.
Thanks,
Muru
The Domain Model should express the business logic in a way that is independent on boundary technologies such as WCF or ASP.NET web services.
This adds the requirement of a third layer:
Service
Domain Model
Data access
If you don't make a separate layer for the technology specific interfaces (Service), you might as well just make a single, monolithic application, because you wouldn't be able to reuse the business logic anyway.
While we're at it: use WCF, not ASMX, for web services.
I would write a web service using ASMX because it's easier to get your head around to start with.
Implement DAL by using ADO or LINQ (might be easier option since it does all the mapping for you and it's good to learn something new imo).
How are you going to call a web service? Did you consider how you will return status code? You can look into JavaScript and Ajax so that you can return custom objects to the client, or you could look into SOAP, which is xml based.
Can also recommend a good read - ASP.Net and Ajax: architecting web applications. Might give you a better idea on what options you have.
i always use the same model: service / business layer and a database layer.
When it comes to Visual studio, i have 4 or 5 projects:
1 with the webservice named project.webservice (which ONLY task it is to receive input and give that input to the layer that does the thinking (business layer), so testing is easyly done to the business layer
1 with the service layer named project.service which does the actual work (decide what the operation should be, call the right db methods etc)
1 with the database logic called project.datalayer which could be ADO.Net code or the Entity framework.
1 with the dataclasses called project.model. These classes are the ones returned by the ADO.Net code and used by the service and the webservice project. If i use a entity framework i normally skip this project, because the EF itself gives me dataclasses the EF generates. Sometimes clients don't want to use the EF dataclasses, then i create the project.model project and let the datalayer translate the EF dataclasses to project.model dataclasses
1 with the testproject named project.test
hop this helps,
Michel
Should the model just be data structures? Where do the services (data access, business logic) sit in MVC?
Lets assume I have a view that shows a list of customer orders. I have a controller class that handles the clicks on the view controls (buttons, etc).
Should the controller kick off the data access code? Think button click, reload order query. Or should this go through the model layer at all?
Any example code would be great!
Generally I implement MVC as follows:
View - Receives data from the controller and generates output. Generally only display logic should appear here. For example, if you wanted to take an existing site and produce a mobile/iPhone version of it, you should be able to do that just by replacing the views (assuming you wanted the same functionality).
Model - Wrap access to data in models. In my apps, all SQL lives in the Model layer, no direct data access is allowed in the Views or Controllers. As Elie points out in another answer, the idea here is to (at least partially) insulate your Controllers/Views from changes in database structure. Models are also a good place to implement logic such as updating a "last modified" date whenever a field changes. If a major data source for your application is an external web service, consider whether wrapping that in a model class.
Controllers - Used to glue Models and Views together. Implement application logic here, validate forms, transfer data from models to views, etc.
For example, in my apps, when a page is requested, the controller will fetch whatever data is required from the models, and pass it to a view to generate the page the user sees. If that page was a form, the form may then be submitted, the controller handles validation, creates the necessary model and uses it to save the data.
If you follow this method, Models end up being quite generic and reusable. Your controllers are of a manageable size and complexity because data access and display has been removed to Models and Views respectively, and your views should be simple enough that a designer (with a little training) could comprehend them.
I wouldn't put Data Access Code in the Controller.
To build on what has already been said, it's important to think of layering WITHIN the layers. For example, you will likely have multiple layers within the Model itself - a Data Access Layer which performs any ORM and Database access and a more abstract layer which represents the Business Objects (without any knowledge of HOW to access their data).
This will allow you to test the components of your system more easily, as it supports mocking.
I like to keep the "contracts", or interfaces, for model persistence or service access in the domain (model) layer. I put implementations of data access or service calls in another layer.
The controllers are instantiated with constructors that take interfaces for the services, e.g. ISomeService, as parameters. The controllers themselves don't know how the service layers are implemented, but they can access them. Then I can easily substitute SqlSomeService or InMemorySomeService.
I've also been fairly happy with a concrete service implementation that takes a domain (model) layer repository as a parameter to its constructor.. For example: ICatalogRepository with SqlServerCatalogRepositry : ICatalogRepository is handed to CatalogService(ICatalogRepository, ISomeOtherDependency).
This kind of separation is easier with dependency injection frameworks.
The View would relay what should happen on a click in the UI to the Control layer, which would contain ALL business logic, and would in turn call the Model layer which would only make database calls. Only the model layer should be making database calls, or you will defeat the purpose of the MVC design pattern.
Think about it this way. Let's say you change your database. You would want to limit the amount of code change required, and keep all those changes together without affecting other pieces of your application. So by keeping all data access in the Model layer, even the simple calls, you limit any changes required to the Model layer. If you were to bypass the Model layer for any reason, you would now have to extend any changes needed to any code that knows about the database, making such maintenance more complex than it should be.