views:

445

answers:

5

Hello, My controllers are getting large and out of hand.

A typical controller does the following:

  • It determines whether a given user has access to a given resource.
  • It validates the ViewModel.
  • It translates the ViewModel into the DTOModel for persistence.
  • It calls repositories to update/create new objects and associated other new objects.
  • It accesses data in multiple repository helper classes
  • It checks whether users get notifiied.
  • It calls helpers to send emails
  • It logs data to the database via other repository objects
  • etc...

In short, they ORCHESTRATE a lot of things. I'd like to move everything into a Services layer, but haven't really seen any implemented patterns in code samples that I like. I've looked at some of the open source projects like KiGG, Oxite, codecampserver, etc...but none of them are really solving the problem of shrinking my Controllers. I'd like to avoid passing around a lot of the HTTPContext stuff, but maybe this isn't possible.

Are there some other projects, best-practices I could be looking at? I'm building a large workflow/data input application.

Thanks for some links and suggestions

A: 

Here at my company we have 5 projects in total:

  • View
  • Controller, in wich we only put the logic for the action methods, and it's helpers
  • Business Logic, where we put the specfic logic for the operations, in you case this would be were the helpers for the emails, the business validations,and where we would call the repositories to update and create objects
  • Data Access, where we put the repositories for queries and data operations.
  • ORM, where we put the Database Model, and classes to exchange data between each layer

In this case, all projects have a reference to the ORM, then, the view has a reference to the controller, the controller to the business logic, and the business logic to the data access.

Tejo
I fail to see how this even attempts to address the question, how to keep controllers from exploding in size.
NickLarsen
Well, from where I see it, putting some of the logic in another layer would reduce the size of the controllers.Creating an base class for the most commom operations would help too
Tejo
More details on this "other layer" business logic layer, is what I'm looking for. Sample designs, patterns, etc...
taudep
What we have here is actually very simple, but our project doesn't seem as big as yours, anyways... Our BusinessLogics are tied to only one Entity, or model object, and they handle operations only with theses tied objects, if needed they can talk to each other, but they don't handle types other than what is defined in their generic parameters.I don't know if this is doable for your project, but here the result is a more organized code..
Tejo
+3  A: 

I don't know of any real examples to show off the top of my head, because I think I came up with my MVC apps's controller -> service -> repository layering scheme based on random questions and answers I found by browsing SO.

However, what I can give you is an example of how to organize the bullets you listed into how it would fit in the way I've structured my service layer. This may not be the best way, but this is how I'm doing my large-scale mvc app. This should give you an idea how to structure it in your own application

My service layer combines one service class per business unit. So if my application has projects, and each project has a person I would have a ProjectService class and a PersonService class.

Based upon your description of how your controllers work, my controller's actions work in the following way.

1) Get the current user's information and call the appropriate service class's authorization method. So if the user is trying to modify a project's details, I would pass the user ID and project ID to the ProjectService's AuthorizeUser method. This means if I change the way I authorize users for projects I only have to change the authorization method and not every controller.

2) Viewmodels are created, saved, and destroyed in the service layer. The service layer takes the viewmodel, validates it (raises an exception or validation result if it fails), and then converts it into a data object, which it will then pass to the repository for saving. It also requests the data object from the repository, converts it into a viewmodel and returns it down to the controller.

3) Logging of all actions occurs in the service layer. This can be automatic based on the action being presented (attempting to save an object to the db) or your controller can explicitly call the service layer to log the action.

The whole point of this is to consolidate common functionality into an easily maintainable layer. If you change how your viewmodel converts into a DTO, it is VERY easy to know where to make the change and to make it once. If you need to change your logging, user access, or even if you want to change how you retrieve certain data from the repositories it is one simple area to change rather than having to hunt down all your controllers and modify them directly.

Edit: This keeps controllers small as they only really contain a few calls to the service layer and that's it (Authorize, perform action, Show View). End Edit

Finally, the asp.net website has a tutorial for performing validation in a service layer. That tutorial can be found here.

KallDrexx
I'm contemplating this answer. I like the idea of service class authorization.
taudep
Just saw the link you edited to add. That's really helpful. Thanks for posting that.
taudep
WIth the linked article you sent, they're doing old-style AddModelError calls for validation. I wonder if there's a way to incorporate the newer Data Annotations validation. (Though, there are validation rules that I write that don't map to attributes.)
taudep
Service based authorization also allows for easier unit testing.
KallDrexx
I have not found a good way to validate DataAnnotations without the MVC framework so far, unfortunately. I am pretty sure there is a way just because it's not in the MVC namespace, but almost every reference to DA is in regards to MVC, including articles talking about how you can't unit test data annotations. If you find a way though I would definitely love to know.
KallDrexx
http://www.codeproject.com/KB/validation/Data_Annotations_with_ASP.aspx looks like it might work for validating Annotations without MVC. It looks like essentially you loop through all the properties, get all the validation attributes for the properties, and run the IsValid() against it.
KallDrexx
+1  A: 

It seems to me like you are relying on your controller to play too many roles.

When designing a controller, I typically think about it as controlling access to a single type of resource. This is to mean for example if I were creating this page you are reading right now, where you can post answers and comments, I would have 2 controllers, one for answers, and another for comments. I would avoid adding two actions to my question controller for unrelated resource access. There are exceptions to this, but they are few and far between.

Also, the basic functionality of each controller is that it should validate the input (even when it is validated in the browser because anyone can edit a request), convert the input into the objects needed to pass to the service layer (or business logic) and validate the response from the service layer before converting it back to objects usable by the view and to serve back to the user. Everything else should be handled in the service layer, keeping the controller thin and predictable.

NickLarsen
Ummm...yeah, the controller's doing a lot in each action. Everything it is doing, however, DOES have to happen with each request. Which is why I'm looking for ideas on how to better break it up into services, etc. I'm not looking to break up a Controller's different actions into multiple actions on a controller, but instead looking to break up lengthy single-action methods into better partitioned parts.
taudep
I realize those things do have to happen on each request, but they do not have to be done by the controller itself. For instance, if the determination that the user should be emailed is based on the data returned from a repository, then perhaps you could add an intermediate layer which passes input to the repository and performs the check before returning the data to the controller. As long as you intentionally regulate each of your objects to a specific and constant set of responsibilities, breaking up the work typically flows naturally.
NickLarsen
A: 

Well, some of that is dependent on what you mean by "the controller is". If your using data annotations for validation and action filters for logging, that's perfectly fine. There isn't any logic in the controller there. Are you using ViewModels and strongly typed views? It seems that the model that your controller is working with should already be the simplified DTO, as opposed to having the full entity and creating a DTO to send back. I have trouble imagining a situation where a controller would send an email, or check that it was sent. That should be handed off to a service layer. I would also look hard at a controller that is operating on "associated objects". It should probably be calling a single method on the repository that handles that.

I haven't opened up Nerd Dinner, so I can't swear to what is in there, but it might be worth examining?

ThatSteveGuy
Yes, I'm using simplified ViewModels that model the data in the UI. The problem is that the view models get broken up into multiple data objects for persistence. There's lots of complex rules in this process, lots of authorization checks, etc...I find Nerd Dinner to be severely lacking in any decent best practices for a real world application. After all, it's based on a database with two tables. Doesn't deal with many-to-many relationships, or any complex data relationship for that matter. I often have business logic that spans 10 tables in a single web request.
taudep
+2  A: 

You should check out this great MVCConf session about Putting Your Controllers On A Diet.

Ryan