Interface between Controller and Service Layer - c#

I am a newbie to .Net MVC and my question today is regarding the MVC pattern.
In our application we have a Service Layer which talks with the DB.
The Controller is Currently talking with the Service layer to get the values from the DB.
Our new Manager requires this service layer interaction from the Models and not from the Controller.
He does say that this architecture is to achieve a thin Controller. We are now starting to port the service layer interaction from controller to models.
And here comes my question. Apart from having a thin Controller, is there any other benefits from enforcing this pattern.
I would like to know the advantages and disadvantages of both pattern.
Some links would also be helpful

Why you shouldn't call services from your ViewModels:
ViewModels are supposed to be classes that contain some data that is interchanged between the View and the Controller. They should not perform any action or retrieve further data. They are dumb models, they don't do anything expect transport data.
What is a View Model
If you are having trouble understanding what a View Model is and what it isn't, think of it like a subset of your model. It only contains data that you need to display on a given view at a given time.

There are 3 types of Models - View Model, Domain Model and Data Model. Check here.
If you are talking about View Models then its a bad idea. There are ways to achieve a thin controller, but ViewModel never should interect with services. If its possible a Controller Action should only invoke a service and throw the result to View. Like this:
[HttpGet]
public ActionResult GetAnimals(int id)
{
var viewModel = new AnimalsService(id).GetViewModel();
return View(viewModel);
}
But in reality many times you can't do that for some obvious reasons. There are few things you can do though. Like don't validate models in controller, you can do that in service layer. Don't hesitate to create more services for different jobs, like pagination, context related logic or some third party api invocation. Create helper or utility classes for repititive codes. Also I think its ok to write fat services.

Related

EF Core, Service and Repository patterns

Just to learn about patterns I'm creating my Web API with these projects:
Entities, Repositories, Service and the API application.
Each controller in APIs use dependency injection to his corresponding service; each service use DI to multiple repositories; Repositories are used to get data from the DbContext and Entities contains DbContext and the DbSets.
As example let's say that when I call the /teams/1 endpoint:
the GetTeam(id) function in controller call _teamService.GetTeam(id);
the service call _teamRepository.GetTeam(id);
the repository does a LINQ call to Context.Team.First(...) a give back to the service the Team entity model;
the service get the model and map it to a DTO that go back to the controller;
the controller give it to the application in JSON format.
Is this a right way to manage the flow?
In addition, imagine that the controller must retrieve the team and all its competitions: is it right to inject the CompetitionRepository and use it from the TeamService? Something like:
TeamService.cs
return new DTOObject {
team = _teamRepo.GetTeam(id),
competitions = _compRepo.GetCompsByTeam(id) <-- is a list
}
I prefer to return entities from my services and not DTOs. The reason is that sometimes the result of a service call is used to create an ASP.NET MVC View Model and sometimes a DTO to return as a JSON. Sometimes the requirements for these DTOs are different, the server side ViewModels can see things that should not be exposed to the client. You can make a DTO in your service layer but in most cases it is just another mapping that you have to take care of for not that much value. This is why I create DTOs or ViewModels directly from entities in the controller.
Also the repository pattern is mostly useless. It might be useful if you change your data store but in practice these kinds of changes come with a lot of other changes to the business logic so most of your service layer is rewritten anyway so the value is lost.

Is it good to have model mapping and more logics in a MVC controller?

Im doing a .NET solution and i have to architect this. So my architecture is like below.
DLL(data logic layer) (Where i have all my repositories to access data)
Models(In a schema wise)
ViewModels(Separately as class library )
Services Layer (Where manipulate data and sends to controller)
Here DLL will sent the data by accessing DB. Then Service layer will use these Repositories (etc. UserRepository) and manipulate the data as i want to send it to controller. In this case controller will return the ViewModels to views.
So what i wanna know is, when mapping data to ViewModels ,Should my service layer do mappings and return ViewModels to Controller ??
OR
Service Layer return as Models and in controller we do the mapping and create view models ?
What i feels is it is not good to have so many operations in the controller. So my service should return ViewModels ,So the controller have less work.
I would like to hear best practices and ideas ??
I would do mapping in the controller. Because there can be some instances we need to map the same service output to different view models. Otherwise, we have to write multiple service methods for each view model type.
You can simplify mapping by using AutoMapper.
Take a look at Where should I put automapper code? question.
It suggest using Automapper in service layer.
Also, configuring mappings is a static method, called only once, so it does not affect performance much: official getting started.
And for end, here is some more explanations for setup: SO answer

What is the role of Controller in MVC model?

I have gone through some answers here and and some articles on MVC but I still have a confusion regarding the role of a Controller in a MVC application.
I read in a book that the Model is self-contained and functions independent of View and Controller. And that the Model contains the business logic and data access codes. Source
Also in the best answer
here
What goes into the "Controller" in "MVC"?
But the other answers around here say that it is the Controller that represent the business logic
Where can I find a dead-simple explanation of MVC?
So which is the correct answer?
Wikipedia states very simply: The controller, accepts input and converts it to commands for the model or view.
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
This answer is correct
Model: This component represents the data and the business logic of the application.The model in the MVC framework is not related to the presentation of the application.The model component focus on keeping track of the state of the application.It also defines business rules for data, means how the data can be changed and manipulated.
View: The view provides the user interface (UI) for the model. The main work (function) of the view represents the information in user understandable format. It uses UI Components such as HTML,CSS,Jquery etc.
Controller: Controller act as a mediator between view and model. it is responsible to control the data transmission between the model and the view. It maps the user action into model updates.The controller layer is helpful to select the most appropriate view and delivers it to the user.
Actually, The Controllers are mediater between the view and model. they don't define the business logic. Models are responsible for business logic.
Controller acts as a mediator between the View and the Model class. It is used just to remove the dependency between model and view classes.
Kindly refer to this link..
https://www.tutorialspoint.com/mvc_framework/mvc_framework_controllers.html
The ASP.NET MVC framework maps URLs to classes that are referred to as controllers. Controllers process incoming requests, handle user input and interactions, and execute appropriate application logic. A controller class typically calls a separate view component to generate the HTML markup for the request.
The Controller class is responsible for the following processing stages:
Locating the appropriate action method to call and validating that it
can be called.
Getting the values to use as the action method's arguments.
Handling all errors that might occur during the execution of the action method.
Providing the default WebFormViewEngine class for rendering ASP.NET page types (views).

Should I inject services into my MVC views?

We're working on some kind of Cloud CMS using ASP.NET MVC technology, and have found some obstacles on the way. There is a number of parameters user could change thru the control panel that we need to end up in Views. For example, Facebook application id to initialize the Facebook JS API. Or additional text to be shown on the page. Or background picture. For now we're not using DI to transfer this parameters, instead we're adding them to the ViewModel, but this ruin the ASP.NET MVC way of working with models (e.g. form validation, bindings etc.)
It looks like that using DI to inject services for providing parameters, texts and pictures could make my views less dependent on controllers specific, and there is even some Microsoft technique to do it http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-dependency-injection#Exercise2. However, there are a lot of answers on forums against injecting services into Views using DI.
So the question: what is a right way to inject some services into Views? Or I shouldn't do it at all and something is wrong in the application design?
UPDATE: some real code examples (now we're using Model to inject the services)
Injecting texts from database (they have to be user-editable, as it is CMS):
<div class="steps">#Html.Raw(Model.Texts["Main", "Step2"]</div>
Injecting translations from database (actually, it is localization):
<div class="gonfalon">#Model.Translations["Title_Winners"]</div>
Injecting parameters (from database, could be request-specific; for example, if the site has different domains, facebook application should be per-domain):
Facebook.Initialize(Model.Parameters["FbApplicationId"], Model.Parameters["FbApplicationSecret"]);
The problem of current approach is that this code has taken from contest mechanic. It is definitely out of contest business scope to deal with custom texts, translations or facebook application Id. Also it ruins the Model as model models not actual business domain but deals with a lot of things actually belongs to View (like translations and custom texts)
UPDATE 2: Have modified the snippet from the answer below to be a bit more generic:
public static class WebViewPageExtensions
{
public static I ResolveService<I>(this WebViewPage page)
{
return DependencyResolver.Current.GetService<I>();
}
}
No, you shouldn't inject services into Views, but...
For scenarios such as theming where you want to give the theme developer more power, just one model isn't enough. If your model contains the current post for example, how can a theme designer asks for a list of categories for the sidebar? Or for a widget?
In asp.net mvc you can use extension methods to offer that functionality.THe extension method will use the dependency resolver to get the service. This way, you can have the needed functionality in the view without actually injecting a service.
Note that calling the business layer to update the model is still a violation of Separation of Concerns. THe services made available to the view should contain only read model or general utility functionality.
An example
public static IMyViewServices MyServices(this WebViewPage view)
{
return DependencyResolver.Current.GetService<IMyViewServices>();
}
IMyViewServices lifetime configured in the DI Container should be per http (scope) request
No, end of story. Why? Here is why:
Your view only needs to know what the view model it's going to be working with to present that model. There are couple of reasons for this but the biggest one is the separation of concerns. Keep your view as stupid as possible. You will see that this seperation will give you a clean application structure throughout the way.
There is a number of parameters user could change through the control panel that we need to end up in Views.
I'm not sure what you exactly mean here but this is why there are view models. Your business layer will shape models up, your controller will simply map them to your view models and pass them into the view (presentation layer).
This really depends on how much or little you want your controllers to do and to what degree of separation you want to achieve.
In my world, the "controller" in an MVC app does as little as possible because I have a service layer handling all of the business logic and a data layer above that handling all of the database interaction.
On a GET, the controller will simply call a service method that will build the view model and hands it back to the controller and the controller passes it on to the view. On POST, the view posts data to the controller which sends it off to the service layer for validation, saving to DB, etc. The service is injected into the controller's constructor.
I'd be more than happy to post code examples if you'd like to see them.

MVC3 - reference to a separate service project in which module?

Initial situation:
I would like to build an MVC3 application with a layered architecture. The layers would be the persistence
layer (repository pattern), service layer and the View layer. I also want to map entities to DTOs in the
persistence layer, and passing these DTOs to the View.
In the View I would like to apply the MVC pattern by using MVC3 weapp. Now my Question is, in which module, the Controller or the Model should i access (reference to) the service layer.
I always see references to the service layer in the controller, like this:
public class CustomerController
{
public ViewResult Details( int id )
{
CustomerDTO customerDto = MyService.GetCustomerById();
return View( customerDto );
}
}
Shouldn't I access the service layer in the Model module? If I access my service layer in the controllers, I don't need the Model module at all...?
I always work on the basis that any real work with the service layer is done in the controller.
If I access my service layer in the controllers, I don't need the Model module at all...?
Incorrect - it is highly unlikely that your service types either will have, or even should have the correct shape and metadata (for example [Display] or [DataType] attribution) or to make them work correctly with MVC views. You should have a Model type for all objects that get given to the view, even if they're one-for-one clones of your service types - because then you have a separation between the data that your view and controllers need and your service types.
If you try to bind your views directly to your service types, then you are creating either one of these two scenarios:
making it harder to change view & controller code because the data being sent to and fro has to conform to service types
making it harder to change service types because to do so would mean changing every view
The ViewModel (or Model, depending on your point of view) is your adapter between what's nice for viewing (displaying on a web page) and binding (receiving from a web page) - and it's simply the case that these two things will often drift apart from the actual service types used at the business logic level. Indeed they should, because they aim to solve different problems.
Depends on whether you want to hide MyService from controller.
In your example it's visible. If you had a method on Model of the same name that then delegated to MyService, it wouldn't be.
Advantage of hiding it is you could swap MyService for YourSevice without impacting the View and Controller layers.
As for no model. Where are you defining your DTOs then? Basically MyService would be your model.
You are also operating on the assumption that the DTO for model to controller to view is the same all the way through, even when adding at least one other layer.
I'd think through that assumption if I were you...

Categories

Resources