Controllers != Business Layer? - asp.net

So I'm assuming people still use a business layer outside just controller logic? If so where's that grey line drawn and what do you not put in your controller classes that you would in your Business Layer project and vice versa? Seems to me like Controllers rid the need for a business layer in your MVC application totally.

The controller layer is part of the view, in my opinion. What you're calling the business layer I call services (not web services; that's just one deployment choice among many).
The business layer knows about use cases and units of work for accomplishing the objectives of users.
The controller is all about validating, binding, and marshaling requests, determining which service is needed to fulfill the request and passing values to it, unmarshaling the response and routing it to the next appropriate view.
So I agree with the hypothesis posed in your title: controller != service.
The classic pattern that came from Smalltalk is Model-View-Controller, which disagrees with my statement by breaking view and controller into separate tiers.
What I'm describing is what is implemented in Java frameworks for both web and desktop. A change in view technology generally means changing the controller as well.
So if the Smalltalk idiom was model-view-controller, the more modern approach would look like view->controller->service->model/persistence. Model means "domain objects", which are independent of all view technologies.

The line is not "grey". It's stark and absolute.
The model (or "business layer") works with any presentation. GUI, command-line, web. And it doesn't require any changes to be wrapped with a GUI (view+control) a Command-line application or a web application.
You know you've done the model ("business layer") correctly when there are no presentation or control features in at all. Further, it's so complete that any GUI can use it directly.

To put it simply:
Controller should contain the application specific logic.
"Business Layer" should contain the business logic.
Following Eric Evans' Domain Driven Approach, the "Business Layer" contains:
Service tier: the interface is designed around the use case scenario
Domain Models: the core domain objects, entities, value objects and more.
Data Access objects: repositories
Also note that the Domain models is not the Data Access tier. It might encapsulate data access, but is not the data access tier itself.

Related

Spring MVC and Web Application Architecture

My understanding of Spring MVC is that the View layer is responsible for the user interface that is populated with data, the Model represents a Map of values made available to the View Layer, and the Controller controls how and what data is passed to the Model as well as what business logic is carried out. The "business logic" can be divided into one or more other layers - generally a Service layer and/or Data Access layer. Is this correct?
I've seen other explanations for the MVC pattern where the Model is considered a layer with Entities, Data Access Objects, and Services. The View is responsible for the user interface. And the Controller is the gateway between the two. I don't think this applies to Spring MVC and other implementations of MVC for web frameworks.
Your understanding as outlined in the first paragraph is mostly correct. Where I differ slightly is in viewing Model, View and Controller as separate layers of an application (since you have references to View layer). MVC is a pattern for implementing user interfaces, which would typically be part of a Presentation layer in an application. There are other patterns for implementing the presentation layer such as MVVM, MVP, PAC, and so on besides MVC.
Spring MVC is built on top of the Spring framework. If you are familiar with the Spring framework you would know that it is one of many available Dependency Injection frameworks for Java. Spring MVC Controllers are regular Spring managed beans that can be discovered by the Spring DI container and can have other Spring beans injected into them.
Model objects in a Spring MVC application can be instances of any Java class, whether in-built data types such as String, Long, BigInteger, etc. or user-defined classes and enumerations.
Views can again be anything meaningful for an end-user - an HTML page, an XML document, a JSON document, a PDF document, an Excel spreadsheet and so on. Spring MVC does not provide any view generating mechanism out-of-the-box. However, it makes available integration to several existing view generation technologies, such as, regular JSPs, JSTL, templating engines such as Freemarker, Java, Thymeleaf and StringTemplate, reporting frameworks such as Jasper Reports, XML binding frameworks such as JAXB and Castor, JSON binding frameworks such as Jackson and GSON, and so on. The Spring MVC API is fairly easy to integrate with view generation technologies and therefore the framework can accommodate new technologies relatively easily.
Since Spring MVC is a presentation layer framework, it does not specify, recommend or enforce how business logic should be implemented. However, it is generally a good idea to keep the business logic out of the presentation layer (see SOLID principle for details). For example, if you wish to provide certain users or business partners programmatic access to your business logic, you would be better off having the business logic in a separate layer of its own which the web presentation layer would invoke. You could then create a thin layer that also invokes the same business logic layer and allows programmatic access to external users using data interchange mechanisms such as SOAP, REST, EDI, etc.
MVC is the UI layer.
A model is a map of objects, representing data for your views. These objects often are JPA entities, but don't have to be. It could be a simple class representing a username and password in a login form.
Keep some logic in model classes. For example, if you want to calculate the interest rate on a loan, you could do this in a model class. For complicated logic, especially when multiple model classes are involved, use a service.
Model classes must be completely independent of views and controllers, in that they can exist without them.
A controller responds to HTTP requests. Generally it is responsible for loading the correct models and choosing the correct view, and returning this info. Controllers should be pretty dumb.
You want "fat models and skinny controllers". Keep as much logic in the model as you can.
A view is a JSP or template (like Thymeleaf or Freemarker) which can consume models. The trick is to have as little logic in a view as possible.

Three-tier architecture and controller

For my application i used an architecture Three-tier, with a service/presentation level, business and datalayer.
Now i want use web api(without MVC, only controller).
Then i think to use a controller like a service, and mantain business and datalayer.
But often the controller logic is linked to the output and to the model present in html.
Another solution could be use the controller that use the service layer to make what the application required. In this case the controller acts as an intermediary between the model on html and the service that could be used by a tablet or other device.
Which software architecture used in these cases?
Three Tiered. You just need to adjust yout misunderstanding what this means.
Your Web API is not a service, it is a UI layer. It naturally does all the UI tuff - like also reforming business data to the needs of a presentation.
A UI is a user interface - it is not necessarily graphical. In the case of a WepApi, the user is the other program using it to pull the data. And naturally the WebApi will do a lot of stuff that you need to do in any front end - user and input sanitation, transformations to the exact need of the presetnation etc. It is the front end, the presetnation and the end of the application's trust boudary (never trust input you get via WebApi) - only that another program uses it, not a person.

Do AOP violate layered architecture for enterprise apps?

The question(as stated in the title) comes to me as recently i was looking at Spring MVC 3.1 with annotation support and also considering DDD for an upcoming project. In the new Spring any POJO with its business methods can be annotated to act as controller, all the concerns that i would have addressed within a Controller class can be expressed exclusively through the annotations.
So, technically i can take any class and wire it to act as controller , the java code is free from any controller specific code, hence the java code could deal with things like checking security , starting txn etc. So will such a class belong to Presentation or Application layer ??
Taking that argument even further , we can pull out things like security, txn mgmt and express them through annotations , thus the java code is now that of the domain object. Will that mean we have fused together the 2 layers? Please clarify
You can't take any POJO and make it a controller. The controller's job is get inputs from the browser, call services, prepare the model for the view, and return the view to dispatch to. It's still a controller. Instead of configuring it through XML and method overrides, you configure it through annotations, that's all.
The code is very far from being free from any controller specific code. It still uses ModelAndView, BindingResult, etc.
I'll approach the question's title, regarding AOP:
AOP does not violate "layered architecture", specifically because by definition it is adding application-wide functionality regardless of the layer the functionality is being used in. The canonical AOP example is logging: not a layer, but a functionality--all layers do logging.
To sort-of tie in AOP to your question, consider transaction management, which may be handled via Spring's AOP mechanism. "Transactions" themselves are not specific to any layer, although any given app may only require transactions in only a single layer. In that case, AOP doesn't violate layered architecture because it's only being applied to a single layer.
In an application where transactions may cross layers IMO it still doesn't violate any layering principles, because where the transactions live isn't really relevant: all that matters is that "this chunk of functionality must be transactional". Even if that transaction spans several app boundaries.
In fact, I'd say that using AOP in such a case specifically preserves layers, because the TX code isn't mechanically reproduced across all those layers, and no single layer needs to wonder (a) if it's being called in a transactional context, or (b) which transactional context it's in.

The Purpose of a Service Layer and ASP.NET MVC 2

In an effort to understand MVC 2 and attempt to get my company to adopt it as a viable platform for future development, I have been doing a lot of reading lately. Having worked with ASP.NET pretty exclusively for the past few years, I had some catching up to do.
Currently, I understand the repository pattern, models, controllers, data annotations, etc. But there is one thing that is keeping me from completely understanding enough to start work on a reference application.
The first is the Service Layer Pattern. I have read many blog posts and questions here on Stack Overflow, but I still don't completely understand the purpose of this pattern. I watched the entire video series at MVCCentral on the Golf Tracker Application and also looked at the demo code he posted and it looks to me like the service layer is just another wrapper around the repository pattern that doesn't perform any work at all.
I also read this post: http://www.asp.net/Learn/mvc/tutorial-38-cs.aspx and it seemed to somewhat answer my question, however, if you are using data annotations to perform your validation, this seems unnecessary.
I have looked for demonstrations, posts, etc. but I can't seem to find anything that simply explains the pattern and gives me compelling evidence to use it.
Can someone please provide me with a 2nd grade (ok, maybe 5th grade) reason to use this pattern, what I would lose if I don't, and what I gain if I do?
In a MVC pattern you have responsibilities separated between the 3 players: Model, View and Controller.
The Model is responsible for doing the business stuff, the View presents the results of the business (providing also input to the business from the user) while the Controller acts like the glue between the Model and the View, separating the inner workings of each from the other.
The Model is usually backed up by a database so you have some DAOs accessing that. Your business does some...well... business and stores or retrieves data in/from the database.
But who coordinates the DAOs? The Controller? No! The Model should.
Enter the Service layer. The Service layer will provide high service to the controller and will manage other (lower level) players (DAOs, other services etc) behind the scenes. It contains the business logic of your app.
What happens if you don't use it?
You will have to put the business logic somewhere and the victim is usually the controller.
If the controller is web centric it will have to receive its input and provide response as HTTP requests, responses. But what if I want to call my app (and get access to the business it provides) from a Windows application which communicates with RPC or some other thing? What then?
Well, you will have to rewrite the controller and make the logic client agnostic. But with the Service layer you already have that. Yyou don't need to rewrite things.
The service layer provides communication with DTOs which are not tied to a specific controller implementation. If the controller (no matter what type of controller) provides the appropriate data (no mater the source) your service layer will do its thing providing a service to the caller and hiding the caller from all responsibilities of the business logic involved.
I have to say I agree with dpb with the above, the wrapper i.e. Service Layer is reusable, mockable, I am currently in the process of including this layer inside my app... here are some of the issues/ requirements I am pondering over (very quickly :p ) that could be off help to youeself...
1. Multiple portals (e.g. Bloggers portal, client portal, internal portal) which will be needed to be accessed by many different users. They all must be separate ASP.NET MVC Applications (an important requirement)
2. Within the apps themselves some calls to the database will be similar, the methods and the way the data is handled from the Repository layer. Without doubt some controllers from each module/ portal will make exactly or an overloaded version of the same call, hence a possible need for a service layer (code to interfaces) which I will then compile in a separate class project.
3.If I create a separate class project for my service layer I may need to do the same for the Data Layer or combine it with the Service Layer and keep the model away from the Web project itself. At least this way as my project grows I can throw out the data access layer (i.e. LinqToSql -> NHibernate), or a team member can without working on any code in any other project. The downside could be they could blow everything up lol...

ASP.Net MVC Architecture - Location of ViewModels

We have a decent sized MVC project running well at the moment, i've started to look at some re-factoring and I have a question.
At the moment the Data Layer and Service Layer is stored in a seperate class library. The controllers load the data objects (generated from linq2sql) from the service layer which does any logic check and then converts them to viewmodels (Using Auto-Mapper).
Instead of this should the ViewModels be returned directly from the service?
Definitely not!
A ViewModel's purpose is to mediate between the view and the 'real' data objects - it's totally view-specific. So layers other than your GUI shouldn't even know that such a model exists, if you want to keep a clean separation of concerns...
I would say not. The point of the service is that it can be used by many different projects that deal with your business layer. I would expect this to be in terms of your business objects. View models are specific to an MVC application and, thus, I would expect them to be separate from the service layer. Note that they often encompass both business and "housekeeping" data for the application, and may encapsulate multiple business objects. I think I would continue to transform them in your controller.

Resources