Chapter 19. Lightweight controllers

 

This chapter covers

  • Using lightweight controllers to simplify programming
  • Managing common view data without filter attributes
  • Deriving action results to apply common behavior
  • Using an application bus

Do you remember those swollen and unwieldy Page_Load methods in Web Forms? Those methods can quickly grow out of control and stage a revolt against your code base.

Controller actions are dangerous too. Nestled snugly between the model and view, controllers are an easy place to put decision-making code, and they’re often mistaken for a good place to put that logic. And it’s quite convenient, at first. It just takes two lines of code to build a select list in an action method. And adding a filter attribute to the controller is a simple way to manage global data for a master page.

But these techniques don’t scale with greater complexity. Orchestrating a process to find a particular order, authorize it, transmit it to the shipping service, and email a receipt to the user, before redirecting the client to the confirmation page? That’s too much for our controller to handle.

19.1. Why lightweight controllers?

It’s important to focus on keeping controllers lightweight. Over time, controllers tend to accumulate more code, and large controllers that have many responsibilities are hard to maintain. They also become hard to test. When creating controllers, think about long-term maintainability, testability, and a single responsibility.

19.1.1. Maintainability

19.2. Managing common view data

19.3. Deriving action results

19.4. Using an application bus

19.5. Summary