Moving Validation, Html Helpers to Service Layer in MVC - asp.net-mvc

We have two WebApplication in one MVC solution, one for Desktop and the other for Mobile version.
The architecture looks like this:
Model Libraray ( including repository and DB Model )
Service Layer ( Business Logic )
Web application Project ( views , controller, viewModels for desktop )
Mobile web project ( Mobile views, controller, viewModel)
I added a service layer into this project http://www.asp.net/mvc/tutorials/validating-with-a-service-layer-cs).
as long as these two web projects have different controller but most common logic , which of following I can move to service layer.
HTML Helper classes
View Model validations
Common functions
Thanks in advance.

First to answer your question of where to position those codes
View Model validations
If there is no particular reason to use the service layer model validation I'd rather advise you to do model validation using data annotations within Model library. All you have to do is to add some attributes to your entities' properties and things will work out of the box including validation messages (if you add validation elements using Html.ValidationMessageFor() or similar) in your client side view.
HTML Helper classes
HTML Helper classes should be part of Common UI library if they're supposed to be shared. They don't belong in any of the existing layers, because all of them are presentation layer (web apps) independent. I suppose your HTML helpers will be presentation layer dependent hence a separate library would suffice.
Common functions
Depending on where you need to use common functions, they may as well be part of Model library or Service layer.
How I structure my web apps
The following are written as layers. They're of course separate projects in the whole solution so they become separate assemblies.
Objects layer - contains all common classes/enums/interfaces, general functionality and application model POCOs used by any layer; that's why it's referenced by all other layers
Data layer - has data access objects (that may as well be inherited from POCOs in the Objects layer) that are only used within this layer and perform mapping to and from application layer POCOs; There are also repositories in this layer hence this layer/assembly is referenced by the next layer (service)
Services layer - contain business logic and manipulate application model classes; gets data from presentation layer and uses Data layer to manipulate data in the backing store (wherever it may be - this is of course part of Data layer repository to communicate with the store)
Presentation layer - may be a web application or anything else; references Objects and Services layer so it's able to communicate; any objects that are presentation layer only are also created here (special view models required by views but not by services);
All these mean that my Objects layer provides means of communication between layers by providing common classes that are used to exchange data between layers.
In cases where there are certain other providers I need to implement they may be part of a separate layer, but upper layering works for the 90% of all applications. A good example would be some common library that gets reused across different applications. Depending on what that library provides it gets referenced by those layers/assemblies that need its functionality.
In you case where you have two web applications, I would create a special layer named Presentation where all common HTML functionality would be and then reference it in both web applications.

Related

Why should we add Model reference separately to MVC front end instead of using it from service reference?

In older web projects that I worked on, we used to create models in DAL, add reference of DAL in Business Logic Layer (and reuse models from DAL as they would be available with reference of DAL), Add reference of BL in Service (again reuse models). Entities were available transitively in all successive layers.
In a MVC project with multiple layers, Models are often added in a separate class library project and referenced across all layers like DAL, Business Logic, Service, FrontEnd etc; Even though they are transitively available.
Is there any specific reason to do this? Why shouldn't we bind Models available through service in frontend like below
#model List<TestSolution.TestServiceRef.Employee>
instead of
#model List<TestSolution.Models.Employee>
What is the advantage of referring models separately in all layers over using it from the reference of another/previous layer?
I don't have a lot of MVC experience (as far as ASP.Net MVC), but as I understand it the Model in MVC is just a representation of the data structures as the coded understands it (i.e. at runtime) - and isn't necessarily the underlying data itself (i.e. database).
If you have a concept that you want to represent in the UI, then obviously the UI needs to know what that concept is - hence referencing it at that level (and other such as the business logic, etc). Pre MVC there was an approach / architecture I followed where the "model" was just a bunch of POCO's (plain old class objects - .e. really simple dumb classes or structs).
These POCO's could go into a an assemply/project like MyApp.Common from where you could safely reference them in any other project / layer of the architecture (UI, Logic, DAL, etc). This allows all layers of the application to "talk the same language", so to speak.
I did a proper write up of this architectural style (which is not MVC, but shares some concepts), here: https://morphological.wordpress.com/2011/08/29/5-layer-architecture/

Queries on Repository Layer in MVC application

I am building MVC 5 application using Razor.
My application is layered as below:
UI Layer: Comprising of Model, View and Controller.
Data Access Layer: Connection and Stored Procedure classes
Business Layer (Service Layer)
Repository
I referred to Contosso Sample Application. There it is using DAL to store Repository. But I am creating a separate layer.
I want to know:
Whether to keep Repository as a separate layer or in DAL?
UI layer Model holds View Models. Where does other models go? Do they reside in Repository Layer? Are these called POCO?
Usually, the Repository is the method of accessing the data and is therefore just an implementation technique of the DAL. I'd combine them both as the DAL.
In terms of other models, I assume you mean the classes that correspond with your data items. These should also live in the DAL/Repository layer. They are referred to as POCOs as they don't contain any implementation, simply a list of properties (plain old CLR object).

MVC architecture large action method on controller

I'm currently developing business logic in a Controller's ActionResult function, and I've noticed it's becoming unwieldy... large... involves a lot of page ups/downs.
Code includes populating lists for dropdownlists assigned to ViewBag properties, but most of the size is taken up EF (linq to entities) and in memory processing of this.
And finally sent to a view model via Auto Mapper.
Where is the best place to move this code? In another class in the Controllers folder? Or in another class in another folder, i.e. a Business layer?
Separate you project to :
WebUI(View, Controller-A MVC Project)
Business Layer(Holds Business Logic - A class Library Project )
Data Access Layer(Holds Entity Model(May be EDMX) - A class Library Project)
A controller of WebUI project call method of business layer.
If business need data from database then, it will call Data Access Layer.
Funnily enough I answered a very similar question yesterday. In a nutshell, limit your controller to just the minimum logic to link your models with your views. Business logic, data access etc. is better placed in a separate repository.
Bappi Datta is right. Let me just explain it from my point of view.
My best practice with the libs AutoMapper, EF is:
Web - includes logic of rendering, some validation, bootstrap configuration. Calls Business layer methods and classes.
Web.Models - web models with validation attributes
BusinessLogic - business layer. Includes mappings EF Entities <---> Web.Models. Uses Data classes.
Data - Here I always put EF Models and context. Also implementation of Repository pattern could be placed there.
You need to have Repository Layer (which you mentioned you already have) and then you need to have a Service Layer which will hold all your necessary business logic probably using patterns like Command Factory and Facades. Then in order for you to have a flexible and easily pluggable architecture, you need to use Dependency Injection between all layers.
Read about MVC architecture in my perspective
There can be different If's and But's in the theoretical discussion of overall MVC architecture itself. But generally your controller actions needs to be thin, you business logic needs to be in a different layer other than repository.

Application design using DDD

I am designing solution strucure for an application. I am planning to use Domain driven design. Asp.net MVC and Entity framework. Need your inputs in some areas.
Data Access is designed using Entity framework code first
Reposirotires are built on top of EF Data Acces
Domain model is designed usind domain model on top of Repositories
Application serveices are built on top of Damain layer
UI is developed on top of Application services
The flow is
UI (controller) --> Application service --> Domain Layer --> Repositories --> Data Access --> Data base.
I am not very clear of how to share the data in between the layers.
My Domain model can be used to sahre data between Repositories, Data Access and Domain Layer. I am just thinking the way the data should be passed from Daomin Layert to Application Service and Application Service to UI. I can use DTOs, But not sure weather it is a good option or not, as i have some models are already in Domain Model, View model in UI.
Reuse Domain Model or UI Model is not good, it will make your layers are tightly coupled. It's very difficult to develop large scale applications that way.
What you think is correct, Application is a thin layer, it's just a bunch of Actions which will be called directly from UI layer and information will be passed through an object called ActionParameter. ActionParameters are defined in Application layer and ActionParameter objects are constructed on UI layer and passed to Application layer.
Application will retrieve data from DB via Data Access Layer. An Query Action sometimes need to fetch data from many source, different domain entities and data need to be projected, transformed or formatted before return to UI layer. We will have something like ActionResult objects that contains all data to be returned to UI layer.
It seems there will be a lot of codes but I think it's necessary. Each layer has its own purpose and when we change one, other layers won't be impacted.
Given the flow you describe, create view models in the UI layer to be instantiated by the controller. A view model is simple object to which the view binds. This should be decoupled from the underlying domain model to address concerns noted by namkha87.
As far as the data access layer, you can use the domain objects themselves for object-relational mapping since EF allows this. There is no need for an intermediate DTO here.
Another thing to consider is separating the model used for queries from one's used to invoke behavior. This way, you can ensure that an application service never exposes behavioral domain objects, only read-models. The problem with having an application service expose domain objects to outer layers is that it will allow those outer layers to invoke behaviors on those objects the results being undefined. When you only return read-only objects with no behaviors, this isn't a problem. For data coming back, don't have the UI layer created domain objects directly - you should distinguish between entities and simple data.

Should a service layer return view models for an MVC application?

Say you have an ASP.NET MVC project and are using a service layer, such as in this contact manager tutorial on the asp.net site: http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs
If you have viewmodels for your views, is the service layer the appropriate place to provide each viewmodel? For instance, in the service layer code sample there is a method
public IEnumerable<Contact> ListContacts()
{
return _repository.ListContacts();
}
If instead you wanted a IEnumerable, should it go in the service layer, or is there somewhere else that is the "correct" place?
Perhaps more appropriately, if you have a separate viewmodel for each view associated with ContactController, should ContactManagerService have a separate method to return each viewmodel? If the service layer is not the proper place, where should viewmodel objects be initialized for use by the controller?
Generally, no.
View models are intended to provide information to and from views and should be specific to the application, as opposed to the general domain. Controllers should orchestrate interaction with repositories, services (I am making some assumptions of the definition of service here), etc and handle building and validating view models, and also contain the logic of determining views to render.
By leaking view models into a "service" layer, you are blurring your layers and now have possible application and presentation specific mixed in with what should focused with domain-level responsibilities.
No, I don't think so. Services should care only about the problem domain, not the view that renders results. Return values should be expressed in terms of domain objects, not views.
As per the traditional approach or theory wise, ViewModel should be part of User interface layer. At least the name says so.
But when you get down to implementing it yourself with Entity Framework, MVC, Repository etc, then you realise something else.
Someone has to map Entity/DB Models with ViewModels(DTO mentioned in the end). Should this be done in [A] the UI layer (by the Controller), or in [B] the Service layer?
I go with Option B. Option A is a no no because of the simple fact that several entity models combine together to form a ViewModel. We may not pass unnecessary data to UI layer, whereas in option B, the service can play with data and pass only the required/minimum to the UI layer after mapping (to the ViewModel).
But still, let us go with option A, put ViewModel in the UI layer(and entity model in Service layer).
If the Service layer needs to map to the ViewModel, then the Service layer need to access ViewModel in UI layer. Which library/project? The Viewmodel should be in a separate project in the UI layer, and this project needs to be referenced by Service Layer. If the ViewModel is not in a separate project, then there is circular reference, so no go. It looks awkward to have Service layer accessing UI layer but still we could cope with it.
But what if there is another UI app using this service? What if there is a mobile app? How different can the ViewModel be? Should the Service access the same view model project? Will all UI projects access the same ViewModel project or they have their own?
After these considerations my answer would be to put the Viewmodel project in Service Layer. Every UI layer has to access the Service layer anyways! And there could be a lot of similar ViewModels that they all could use (hence mapping becomes easier for service layer). Mappings are done through linq these days, which is another plus.
Lastly, there is this discussion about DTO. And also about data annotation in ViewModels. ViewModels with data annotations(Microsoft.Web.Mvc.DataAnnotations.dll) cannot reside in service layer instead they reside in UI layer(but ComponentModel.DataAnnotations.dll can reside in service layer). If all projects are in one solution(.sln), then it doesn't matter which layer you put it. In enterprise applications, each layer will have its own solution.
So DTO actually is a ViewModel because mostly there will be one on one mapping between the two(say with AutoMapper). Again DTO still has the logic needed for the UI(or multiple applications) and resides in Service Layer. And the UI layer ViewModel(if we use Microsoft.Web.Mvc.DataAnnotations.dll) is just to copy the data from DTO, with some 'behavior'/attributes added to it.
[Now this discussion is about to take an interesting turn read on...:I]
And don't think data-annotation attributes are just for UI. If you limit the validation using System.ComponentModel.DataAnnotations.dll
then the same ViewModel can also be used for front-end & backend validation(thus removing UI-residing-ViewModel-copy-of-DTO). Moreover attributes can also be used in entity models. Eg: using .tt, Entity Framework data models can be autogenerated with validation attributes to do some DB validations like max-length before sending to the back end. This saves round-trips from UI to backend for validation. It also enables back-end to re-validate for security reasons. So a model is a self-reliant validator and you can pass it around easily. Another advantage is that if backend validation changes in DB then .tt (reads DB specifics and create the attribute for entity class) will automatically pick that up. This can force UI validation unit tests to fail as well, which is a big plus(so we can correct it and inform all UIs/consumers instead of accidentally forgetting and failing). Yes, the discussion is moving towards a good framework design. As you can see it is all related: tier-wise validation, unit test strategy, caching strategy, etc.
Although not directly related to the question. 'ViewModel Façade' mentioned in this must watch channel 9 link is also worth exploring. It starts exactly at 11 minutes 49 seconds in the video. Because this would be the next step/thought once your current question given above is sorted out: 'How to organize ViewModels?'
And Lastly, many of these model vs logic issues could be resolved with REST. Because every client can have the intelligence to query the data and get only the data that it needs. And it keeps the model in UI, there is no server/service layer model/logic. The only duplication then will be on the automated tests that each client need to perform. Also if there are changes in data then some clients fail if they do not adapt to the change. The question then is, are you removing service layer altogether(and the models they carry) or pushing the service layer up to your UI project(so model issue still persists) which calls the REST API. But in terms of the responsibility of Service layer, they are the same regardless.
Also in your example "_repository.ListContacts()" is returning a ViewModel from repository. This is not a mature way. Repositories should provide entity models or DB models. This gets converted to view models and it is this view model that is returned by the service layer.
This has come a bit of an "it depends" where I work - we have generally had a controller consuming some service(s) - then combining returned DTO's into a 'ViewModel' that would then get passed to the client - either via JSON result, or bound in the Razor Template.
Thing is, about 80% of the time - the mapping of DTO to ViewModel has been 1-1. We are starting to move towards 'Where needed, just consume the DTO directly, but when the DTO and what we need in our client/view don't match up - then we create a ViewModel and do the mapping between objects as needed'.
Although I'm still not convinced that this is the best or right solution - as it ends up leading to some heated discussions of 'are we just adding X to the DTO to meet the needs of the view?'
I suppose that depends on what you consider the "services" to be. I've never really liked the term service in the context of a single class; it's incredibly vague and doesn't tell you much about the actual purpose of the class.
If the "service layer" is a physical layer, such as a web service, then absolutely not; services in an SOA context should expose domain/business operations, not data and not presentation logic. But if service is just being used as an abstract concept for a further level of encapsulation, I don't see any problem with using it the way you desribe.
Just don't mix concepts. If your service deals with view models then it should be a presentation service and be layered over top of the actual Model, never directly touching the database or any business logic.
Hi I see very good answers here.
And for myself I do an other aproach.
I have to kinds of models , one is viewmodel and the other is shared models. The viewmodels stays on the UI layer and the shared models stays on a separate project.
The shared models can theoretically be used anyware because those are standalone.
This models provides some abstraction if you want to return specific data from your service layer or if you need something specific from your repository.
I don't really know if this is a good aproach but it works so well on my projects. For example
When I need to provide some information to create new objects to the database i can use the shared models directly to the service layer it saves me some complexity.
The shared models needs to be mapped sometimes , but you can ensure that your service is not leaking inesssary data to the UI.
You can see shared models as an extension but not to build your UI logic with it, you should have viewmodels to do that.
You can combine viewmodels with this shared models to save you time you can use inheritance.
The shared models has to be neutral and should not have any kind of logic.

Resources