Put your controllers on a diet: GETs and queries

Previous posts in this series:

In the last post, we surveyed the field to determine the path forward. Looking at our controller (and others), our controllers aren’t too messy, but they’re well on their way. On top of that, testing is going to start to get annoying if I have any more things going on.

It was also clear once we defactored that there is a clear delineation between our GET and POST actions. This is natural, as GETs are a browser asking a server for information and a POST is a request to modify information or do something. Let’s take these one at a time.

GETs to queries

Our GET actions are almost identical:

public ViewResult Show(string eventName)
{
    var conf = _session
        .Query<Conference>()
        .SingleOrDefault(c => c.Name == eventName);

    var model = new ConferenceShowModel
    {
        Name = conf.Name,
        Sessions = conf.GetSessions()
            .Select(s => new ConferenceShowModel.SessionModel
            {
                Title = s.Title,
                SpeakerFirstName = s.Speaker.FirstName,
                SpeakerLastName = s.Speaker.LastName,
            }).ToArray()
    };

    return View(model);
}

I take in some parameter from the action, use it to query the database, then map that result into a View Model. Finally, I pass that View Model into a ViewResult, and I’m done. As far as items I control, I see three distinct steps:

  1. Query database
  2. Build View Model
  3. Create ViewResult

If I were to pull things out of the controller action, which of these steps should I remove? Step 1 feels obvious, it has nothing to do with UI concerns. Step 3 seems like it should stay in the controller, since a ViewResult is a UI concern (and the method to easily build one resides in a base Controller class). What about Step 2?

For more complex models, I often have to compose several pieces together into one model. I might need to make more than one query to the database, or compose data from different services. Ultimately, this all results in one View Model. Since the View Model building can get complex and touch one or more backend services, I’ll also pull that out.

Let’s pull that piece out into a separate class, called “ShowHandler”, since it handles the bulk of the work of the Show action:

public class ShowHandler
{
    private readonly ISession _session;

    public ShowHandler(ISession session)
    {
        _session = session;
    }

    public ConferenceShowModel Handle(string eventName)
    {
        var conf = _session
            .Query<Conference>()
            .SingleOrDefault(c => c.Name == eventName);

        var model = new ConferenceShowModel
        {
            Name = conf.Name,
            Sessions = conf.GetSessions()
                .Select(s => new ConferenceShowModel.SessionModel
                {
                    Title = s.Title,
                    SpeakerFirstName = s.Speaker.FirstName,
                    SpeakerLastName = s.Speaker.LastName,
                }).ToArray()
        };

        return model;
    }
}

My controller action is now quite small and manageable:

public ViewResult Show(string eventName)
{
    var model = _showHandler.Handle(eventName);

    return View(model);
}

The “_showHandler” variable is just a constructor injected instance of the ShowHandler class created above.

I like what we have so far, but I do foresee one problem here. If I get more parameters to my controller action, I’ll have to modify the signature of the Handle method. That can get annoying, so why don’t we create a class to represent the parameters of that call? And since we’re looking at “requests” of information, that pattern is typically called a Query. Our ShowQuery class now encapsulates that request for information:

public class ShowQuery
{
    public string EventName { get; set; }
}

The controller action can now take this query object as a parameter (also helping with refactoring efforts when we use parameter objects):

public ViewResult Show(ShowQuery query)
{
    var model = _showHandler.Handle(query);

    return View(model);
}

All my URLs still look the same, I’ve simply encapsulated all action parameters into a single type. This type is then passed all the way down to my handler:

public ConferenceShowModel Handle(ShowQuery query)
{
    var conf = _session
        .Query<Conference>()
        .SingleOrDefault(c => c.Name == query.EventName);

    //snip
}

I now have the querying to build a View Model completely encapsulated in a handler, and my controller is now responsible for delegation and ActionResult creation.

Obligatory AutoMapper refactoring

Most folks probably guessed this, but let’s get rid of those calls to build up a View Model. I can use AutoMapper and the LINQ projection capabilities to eliminate nearly all of the mapping code. After creating maps between my source/destination types, my handler starts to become pretty small:

public ConferenceShowModel Handle(ShowQuery query)
{
    var model = _session
        .Query<Conference>()
        .Where(c => c.Name == query.EventName)
        .Project().To<ConferenceShowModel>()
        .SingleOrDefault();

    return model;
}

After creating handlers for my other controller actions, they also become fairly small:

public ConferenceListModel[] Handle(IndexQuery query)
{
    var minSessions = query.MinSessions ?? 0;

    var list = _session
        .Query<Conference>()
        .Where(c => c.SessionCount >= minSessions)
        .Project().To<ConferenceListModel>()
        .ToArray();

    return list;
}

And my edit handler:

public ConferenceEditModel Handle(EditQuery query)
{
    var model = _session
        .Query<Conference>()
        .Where(c => c.Name == query.EventName)
        .Project().To<ConferenceEditModel>()
        .SingleOrDefault();

    return model;
}

Queryable extensions project at the LINQ level, meaning it alters the actual query at the ORM layer (and eventually the SQL layer). I don’t return tracked entities, I project directly from SQL into a DTO. The Project().To<Foo> methods alter the expression tree created by IQueryable to include AutoMapper projections. Cool stuff!

Our controller actions are now small, and somewhat uniform:

public ActionResult Index(IndexQuery query)
{
    var model = _indexQueryHandler.Handle(query);

    return View(model);
}

public ViewResult Show(ShowQuery query)
{
    var model = _showQueryHandler.Handle(query);

    return View(model);
}

public ActionResult Edit(EditQuery query)
{
    var model = _editQueryHandler.Handle(query);

    return View(model);
}

However, something’s still a bit off. We have to take all these handlers as constructor arguments, and that will get annoying. What I’d rather do is not depend directly on handlers, but instead shoot the query off to…something…and have that something return my result. I want something to mediate between my request for information and the handler getting the result. Sounds like the Mediator pattern!

Mediators and diminutive buses

If we want to pull all our queries behind a common abstraction, we first need to make sure all of our query handlers “look the same”. With our introduction of a query object, they all have the basic form of “class with one public method, one input and one output”. For the lazy, this pattern is already abstracted into the ShortBus project from Matt Hinze. I don’t feel lazy, so let’s just build this from scratch. We’ll first create an interface representing our queries:

public interface IQuery<out TResponse> { }

This is the interface our query objects will use, with a generic parameter annotating what result this query will represent. Next, an interface to represent our query handlers:

public interface IQueryHandler<in TQuery, out TResponse>
    where TQuery : IQuery<TResponse>
{
    TResponse Handle(TQuery query);
}

Finally, our mediator interface:

public interface IMediator
{
    TResponse Request<TResponse>(IQuery<TResponse> query);
}

I’ll leave it as an exercise to the reader to implement our mediator, or just grab the ShortBus code/NuGet goodness. Our ShowQuery becomes:

public class ShowQuery
    : IQuery<ConferenceShowModel>
{
    public string EventName { get; set; }
}

And the handler doesn’t change except for an interface implementation:

public class ShowQueryHandler 
    : IQueryHandler<ShowQuery, ConferenceShowModel>

Repeating this exercise for all of my queries/handlers, our controller starts to look pretty darn good:

public class ConferenceController : Controller
{
    private readonly ISession _session;
    private readonly IMediator _mediator;

    public ConferenceController(ISession session, IMediator mediator)
    {
        _session = session;
        _mediator = mediator;
    }

    public ActionResult Index(IndexQuery query)
    {
        var model = _mediator.Request(query);

        return View(model);
    }

    public ViewResult Show(ShowQuery query)
    {
        var model = _mediator.Request(query);

        return View(model);
    }

    public ActionResult Edit(EditQuery query)
    {
        var model = _mediator.Request(query);

        return View(model);
    }

That’s pretty much it! I might have other UI concerns going in my controller action, but the work to actually take the request and build a model is behind a uniform interface, mediated through our mediator, and easily testable in isolation from any UI work that needs to happen.

At this point, I’d likely give a hard look at feature folders in ASP.NET MVC. This class explosion is necessary to decompose my application into distinct, well-defined parts, but having too many “EditQuery” objects in one folder is annoying. Putting each view/query/handler/view model in a common controller folder is a path to sanity.

Next up: POST actions.

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Jimmy Bogard

I'm a technical architect with Headspring in Austin, TX. I focus on DDD, distributed systems, and any other acronym-centric design/architecture/methodology. I created AutoMapper and am a co-author of the ASP.NET MVC in Action books.
This entry was posted in Architecture, ASP.NET MVC, Design. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Pingback: Put your controllers on a diet: GETs and querie...

  • Joseph Daigle

    As our project became more complex, this is preciously the pattern that we evolved to: command and query objects that are sent to a mediator from the front-end to dedicated handler objects.

    The added advantage, for us anyway, is that this naturally became the application’s API. Other services and components that ran in the backend (background workers, scheduled tasks, etc) could use the exact same commands and queries to interact with the system. You could also stand-up new front-ends without having to rewrite all of the backend application logic.

    Additionally, integration testing became much easier. Using your favorite testing framework and implementing tests or specs using commands and queries ends up being extremely clean.

  • Andrei Volkov

    Been doing the same for ~3 years now. Our query handlers are even called the same, query handlers. Our Mediator is called Dispatcher and relies on Autofac for its magic.

  • AlexanderTank

    I would like to see how you reuse query handlers or compose complex view models that consist of other view models.

    • jbogard

      I don’t re-use query handlers in the general sense. There’s always a scoped view model/query for that controller action. Inside that main handler, I *might* re-use additional general purpose queries, but that turns out to be quite rare. I’m less concerned about duplication and more about isolation, if that makes sense.

      There are cases where I re-use filters/WHERE clauses, but I go different routes for that.

      • Patrick Hitch

        I would love to see a post on how you reuse filters. I’ve been enjoying the other posts in the series.

  • Michael

    What about model state errors? What about bailing early from action based on incoming parameters with RedirectToAction and HttpNotFound results? And what about reusing the same initialization for some properties of the model (SelectListItem lists for drop downs need to be filled from database on both get and post Edit actions)?

    • jbogard

      Do you think this post needed to be EVEN LONGER? I’ll get there after POSTs :)

  • Michael Hart

    Maybe looking “pretty darn good” is a matter of perspective :-) Seems like the controller’s become anorexic to me! It’s certainly anaemic, appears to have nothing to do with conferences, has three methods with the same code in it, and has introduced yet another layer of abstraction.

    The next person who looks at this code is going to have little idea what’s going on, and is going to need to dig through various IoC wiring classes to try and make sense of it.

    Is there a way you can show that this isn’t just architecture for the sake of it, dragging us back into the EE days?

    Perhaps it needs a more real-world example to show why/how it’s useful?

    • kamranayub

      I can’t speak to this pattern shown above, but in the past I’ve done a similar thing using a “service” (not a web service, just a service class) which I can then encapsulate the view model building and any other business logic. This is helpful because:

      a. I only need to test the service layer and up, because my controllers are lean and clean. No dependencies on mocking HttpContext or other web concerns.

      b. I can use the same exact calls in my Web API. I don’t like using my controllers for an API (though you could), so it helps when I can use the same service dependencies in my API controllers and MVC controllers.

      It’s a bit less abstract than this. On the last app we did this with (at work) we’ve had good luck maintaining the app over time (production application, last I touched it was 1.5 years ago and it’s been maintained by multiple developers since then).

      We also return a generic “result”-esque class from service calls so we can easily encapsulate error handling and success/error messaging for the UI.

    • jbogard

      Believe it or not, I agree with you! On the surface, this refactoring is a bit pointless (ok maybe more than a bit). My previous post digs into the reasoning. The gist of it is, if we just have this going on, defactoring is better than refactoring. However, as our application grows, we might be more concerned about consistency and testability. With handlers being one-model-in, one-model-out, and NO UI concerns, I don’t have to mock those pieces.

      On the complexity side, our developers (junior all the way up) actually prefer this approach for its simplicity. Controllers don’t get big, and all logic for a request, except that tiny piece to satisfy ASP.NET MVC, is in exactly one spot. It can grow as complex as it needs without affecting the rest of the class.

      I do struggle with providing “real world” examples, since my real world is actual client code, that I can’t show. Hopefully this provides some context!

      • Michael Hart

        I guess perhaps that’s the crux – that the controller itself is too hard to test (?) due to friction with the ASP.NET MVC framework, even though it appears quite simple – so you really have to delegate everything to the next layer to have control of it.

        It’s a pity that this is the way things are – it kinda feels like the controller shouldn’t even be written at all if that’s the case (ie, just abstract it out completely and establish a convention that allows you to only ever write “query”/”mediator” classes) – or that testing it should be a lot easier, in which case you don’t need to have yet another layer that you need to jump through.

        I’ve always liked the idea that the controllers should at least be responsible for dealing with any incoming data and determining the flow from there and back via the request (ie, returning a 200 OK, or redirecting somewhere, etc, etc). ie, I should be able to get a basic understanding of the high level flow of a particular route by reading the controller. If all of that logic is handled by other pieces of the system, then what’s the point of having the controller at all really?

        • jbogard

          And that’s one of my annoyances with MVC – it shoves many different requests in a single class. Many other web frameworks eschewed controllers altogether and opted instead for individual handlers for this very reason.
          Although, I think there is something to be said for separating the domain level concerns of commands/queries and the UI concerns of request routing and HTTP result building. Unfortunately, MVC is still too heavyweight to combine both activities (see ModelState to check validation errors, for one)

          • http://www.Marisic.Net/ dotnetchris

            Some of those fall into the antipattern of service explosion. You now have a billion tiny pieces you need to keep track of. The opposite of the god controller.

            MVC controllers work really well when they’re kept dead simple. Honestly I’ve been very disappointed with WebApi, it’s very unlikely I will ever use it (maybe by 3.0 they’ll get it right, as the Microsoft version 3 proverb goes). MVC seems to give me everything i need OOB except good conneg.

          • http://www.joshka.net/ Joshua McKinney

            What makes this an anti-pattern?

          • http://www.Marisic.Net/ dotnetchris

            Zero encapsulation, stove pipe cluster fuck. http://sourcemaking.com/antipatterns/stovepipe-system

          • http://www.joshka.net/ Joshua McKinney

            I’m not sure that I follow your argument. Could you perhaps expand on this? To me the stovepipe seems like something that would come from services / classes having a wide horizontal surface area (many methods with a low degree of relatedness), leading to many incoming and outgoing (vertical) linkages to other parts of the system. Whereas the proposed solution mitigates this issue.

          • http://www.Marisic.Net/ dotnetchris

            Stove pipe systems have zero cohesion. By having dozens and hundreds of actions that encapsulate nothing, you have created a stove pipe system. You can create a stove pipe system from bad encapsulation that you have classes that connect all over the place.

            The system you propose of using the 1:1 stuff while being the opposite of brittle, it has maintenance nightmare implications, it can easily be a code reuse nightmare. Actions that are closely related belong together. A ProjectController that handles all routes of /projects, list, view, create, edit, delete is great cohesion and allows reusability inside the controller if there are commonalities. The opposite having ProjectCreate, ProjectList, ProjectView, ProjectEdit, ProjectDelete offers no cohesion. if there are any attempts of code reuse in those actions you have no idea what impacts making changes to the code will have without using analysis.

          • http://www.joshka.net/ Joshua McKinney

            I think I see your point. If you’re just doing CRUD, there is very little cohesion to be had from splitting this up. In the case of anything beyond that (and it’s fairly often that business domains end up going beyond CRUD), a controller per workflow makes sense.

            My example above is the account controller. In this example there are the following workflows with associated states (in brackets):
            * Login (enter login details, login success, login failed due to non-existant / invalid password, too many tries, login failed due to non-confirmed email) – AccountLoginController.
            * Registration (enter details, registration success, registration failed due to mandatory details, failed due to conflicts like duplicate username) – AccountRegistrationController
            * password reset (enter details, details accepted reset email sent, reset link clicked enter new password, new password accepted) – AccountPasswordResetController
            … etc.

            I posit that each of these flows should be separate controllers, which simplifies a number of things related (unit / integration / UI tests, etc.). There is a coherence and SRP adherence that is obvious (these actions are the UI for this workflow), while things that don’t belong in the controllers look obviously out of place if they are in the wrong place.

            I’m not sure that I follow your logic about attempting code reuse. In my mind, code reuse should never be a goal, but instead a side-effect of appropriate refactoring. I often see solutions where designing for reuse obscures the readability and maintainability of the solution to the specific problem. I think your point supports this view. It may go without saying that frameworks fall outside of this discussion and I’m talking purely about application level code here.

          • http://www.Marisic.Net/ dotnetchris

            Yes exactly with your examples of those controllers. Using your very same examples, you very well might have all of the action methods in AccountLoginController using the same POST validation. AccountRegistrationController might have all action methods use the same ModelViewModel mapping.

            The code related to my scenarios is likely highly specific to that individual controller and would likely only make sense encapsulated in that controller. But suppose you have each of those actions broken out to minute classes. You’re going to be looking at sharing that code either through a base class, or through public classes. At this point you’re maintaining multiple files for one cohesive unit, perhaps PasswordValidation that’s for AccountLoginController appears to be applicable to AccountPasswordResetController, and now reset password to inadvertently skip an important validation. Or the opposite, they’re using the same password validation and you a CAPTCHA to ResetPassword and update the validation accordingly and now no user can log in because the login view has no CAPTCHA to ever possibly validate successfully. Lets go one other direction, instead of the controller sharing relevant validation for methods, you now add CAPTCHA to everything and have to update 2, 3, 5, 10 different items.

            While my examples are all contrived, when in reality people always manage to do even more spectacular ways to shoot themselves in the foot when they’re coding in a bubble.

          • http://www.joshka.net/ Joshua McKinney

            I’m not sure whether you’re agreeing or disagreeing with what I wrote at this point. I would generally not suggest re-using viewmodels at all. E.g. whilst the fields edited in a Create and an Edit workflow start out very similar, they seem to diverge as soon as you introduce any business logic. Hence tying the ViewModels to the domain object is an anti-pattern in my opinion. Instead ViewModels belong to the View and the workflow that manages that view.

            In your last paragraph you’re calling for input model validation to be re-used. I agree with this. Generally I’d start with a view model implements IValidatableObject for input validation, then if there is common validation parts, this will get refactored to a class / validation attribute.

            On your CAPTCHA point. I’m not sure that I follow. You seem to be suggesting that it’s easy to get into a situation where you accidentally do things by coincidence. This doesn’t sound particularly fun. I think I’d prefer to program deliberately and hence choose the latter. Alternatively if there is an element of common functionality, pulling that into a reusable form.

            Perhaps a better example of this might be ensuring that a password meets certain strength validation. Perhaps seeing this then as a sub view model of the AccountRegistrationViewModel, PasswordResetViewModel as well as the AccountProfileEditViewModel of type PasswordChangeViewModel, which requires duplicate entry of the password and allows reuse of the strength validation (either as an validation method on the view model, attribute, or backend process for more complex checks like cannot match previous 10 passwords). I don’t see that this view is discordant with either of our views, but I also don’t see how this view says anything about needing to have model explosion. In my mind there is exactly the number of models that is required by the separate workflows. No more, no less. Conflating these leads to a higher maintenance burden than not.

          • https://twitter.com/memark Magnus Markling

            What’s your major disappointment with WebApi? I’ll agree they’re not perfect, but that applies to ordinary MVC controllers as well I think.

          • http://www.joshka.net/ Joshua McKinney

            Controller per business workflow might help this problem with MVC. E.g. the UserRegistrationController rather than the AccountController.

          • James Nail

            Jimmy, your comment about separating the domain-level concerns of commands/queries and the UI concerns of request routing and HTTP result building gets right to the crux of what I’m grinding against right now.

            On one hand, I implemented an in-memory synchronous bus (very similar to ShortBus), where my handlers would function as my application/use case layer (which would be agnostic to the host app — meaning no UI / presentation models, etc.).

            On the other hand, now I need another mechanism to adapt those results (DTOs) to presentation/view models, and to handle those concerns that Michael mentions (validation / model state errors, early exit -> redirect to action, etc.). Of course I say I need a mechanism for this because I’d like a uniform approach, and because ASP.Net MVC is so god-awful from a testability (and SRP) perspective, I definitely don’t want that stuff in my controllers.

            It really sucks that we have to jump through so many hoops to work around MVC’s shortcomings. Maybe it’s just time to jump into FubuMVC, NancyFx, or Simple.Web.

          • jbogard

            You know, that last solution might just be the best, to be perfectly honest.

      • http://www.Marisic.Net/ dotnetchris

        Well said. This can be summarized “volatility has been encapsulated”.

        You only need to change the controller for changes in route driving. You only need to change the business classes for business changes.

        SRP win.

    • http://www.Marisic.Net/ dotnetchris

      Controllers absolutely should be anemic. There should be nothing done in controllers except route driving.

      Controllers stitch HTTP input to business classes. Controllers are not business classes and should not contain business logic.

      • Nathan Alden

        Writing those things should make you wonder why we are being told to use controllers in the first place. This abstraction-upon-abstraction issue is exactly why I wrote my own routing framework that gets your from HTTP request to code method without forcing a model (MVC) on you that shouldn’t apply to a stateless protocol (HTTP).

      • Nathan Alden

        Writing those things should make you wonder why we are being told to use controllers in the first place. This abstraction-upon-abstraction issue is one reason why I wrote my own routing framework (JuniorRoute) that gets your from HTTP request to code method without forcing a model (MVC) on you–a model that doesn’t work well with a stateless protocol (HTTP).

    • Craig Wagner

      As I was reading the article I was composing a response in my mind. Then I read this response and threw away everything I had mentally written because this covers everything I wanted to say.

      I’m good with a certain amount of abstraction to support unit testing (e.g. wrapping data access into some sort of DAL class), but some of this just seems pointless. I can hear some of the justifications now… “It makes the controller easier to test.” There’s nothing there to test. “It makes the business logic easier to test.” No it doesn’t, the business logic is exactly the same, it just lives somewhere else. “I can reuse my business logic.” No, you’re creating ViewModels that are tied to a particular view, that code isn’t reusable.

      Maybe I’m just one of those “dark matter developers” that Hanselman likes to reference. I don’t think so, I do try to stay abreast with technology and encourage my organization to stay abreast, but sometimes this stuff just feels like “but, but, but, we’re an *enterprise*” justification.

      • jbogard

        I agree, that’s why on the previous post I went in to why you *wouldn’t* do this. This type of pattern is only really useful if your controllers get complex, and want something besides a bunch of service classes to get in the way. Probably the most valuable thing in this series is the defactoring part, where I removed all those pesky abstractions to get at the meat of what my app was actually doing, and ONLY then did I make a decision to figure out where to go from here. Most apps I’d say defactor first, then decide if you need any refactoring from there (i.e., destroy your repositories/DAL etc etc)

        In our system, we arrived at this pattern because we had dozens of controllers and 100s of actions, and needed a common way to reason about all of them. Finding a common model for commands/queries was our final result.

        • http://muddypa.ws nportelli

          I know your example for these articles is probably small for the sake of not confusing the topic, but I wish our controllers looked like your defactored ones even.

          Most of our controllers are huge beasts filled with conditions for different permission levels, etc. How do you handle things like that?

        • Long duck

          Sorry, but what’s the point of demonstrating an architecture that doesn’t actually solve a problem in this case?

  • Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1474

  • Ahmed

    Hi Jimmy, thanks for this post i was thinking about pushing this further ! i started a discussion with Rinat abdullin on twitter about the idea to wire-up directly my URL to my query and commands, i gave an example of url : Billing/PlaceOrder (post) that will trigger the handlers of the command PlaceOrder in my Billing bounded context (namespace and folder feature) , i try to do this with web api but the more important is the approach, what you think about it ?? i want to have an infrastructure that take careof this for me and like in hexagonal architecture provide a Http port for triggering my command and queries independetly from the technology ? can i have your feedback ? do you think it is a good idea

    • jbogard

      Yes, this is possible, but not easily with ASP.NET MVC. Some other frameworks take a “Model-View-Handler” approach. And, yes, I do like this idea :)

      • Ahmed

        Yes, i’m looking to do it with Web API in fact, but the main point is to make it as a port for my domain (as in hexagonal architecture), create an adapter that can be switched for wpf, web api or message queues as a way to communicate with messages (i consider command and queries as messages) so i try to isolate that from technologie. With Web api there is a couple of choices since there is many extensibility options (message pipeline, control resolver, or routing ) it is still a work in progress. For ASp mvc it is similar to having single action controller (which in fact is my query or command). But as i said it is still a work in progress and ‘m studying many options :)

        • Kyrillm

          Have a look at https://github.com/ServiceStack/ServiceStack, each controller’s action takes a message and returns a message, incoming message is a query, outgoing one is a ViewModel – simple, clean and gives seamless integration with message bus if you need it

  • http://au.linkedin.com/in/afifmohammed Afif Mohammed

    I don’t get all the people commenting here who are complaining over ‘abstractions for the sake of it’. Seriously? If you look closely there are only three abstractions, a query, a command and a mediator. As a developer you are only writing a query or a command. The mediator knows which query or command to invoke based on the provided request. And the controller calls the mediator with the request its provided from the user.
    Imagine how easy it is to explain this to new starters when you show them you either have to write a query or a command, every thing is so modular.
    Compare this to having x repositories and having x services, and an interface for every one of those because its easier to test. Your interfaces are you abstractions, and when you blindly follow the repository pattern with services on top and then define an interface for every one of them, you have as many abstractions as you have classes, that is called having abstractions for the sake of it.
    I have used this command and query object pattern very successfully in large scale distributed applications across many production apps over the last three years. It makes life so simple!

  • http://harriyott.com Simon Harriyott

    I’m very much enjoying this series, and looking forward to the next post.

  • Pablito

    From a developper standpoint I like the approach, from a Web server standpoint I’d be curious to see the before/after for the %time in GC counter under load.

  • mxmissile

    I must be missing something here. Say I have 20 controllers in my project each with ActionResult Show(int id). This would require me to write 20 separate class like this:
    public class ShowQuery
    {
    public int Id { get; set; }
    }

    Am I right?

    • mxmissile

      And your action links go from
      @(Html.ActionLink<TasksController>(x => x.Show(123),"show")))

      to this
      @(Html.ActionLink<TasksController>(x => x.Show(new ShowQuery{Id = 123}),"show")))

      Not really a big deal but… maybe all this falls under "it depends"?

      • jbogard

        Yeah, we’ll pretty much only create queries if the query is…interesting for whatever your definition of interesting is.

        Also, we don’t always make the controller action parameter the query. We’ll typically start with just ID and add a query if the query has more than one parameter that gets passed in the action.

        • Morten Korsgaard

          Hi Jimmy, if you do not create queries then how do you “handle” them, since the IQueryHandler requires a Type as generic input ?

          Do you have another Handler for primitive types/string, or do you use a different pattern for when you just need to “QueryById” or other simple parameters?

          Btw. great series, looking forward to the next post :-)

          • jbogard

            I’ll always create a query for that scenario. If the query is simple, I’ll skip the query object and just use the ISession directly.

  • http://www.kizi1.org/ Kizi

    these are very useful and share it with many things that I’m waiting the next, good luck

  • Mike Cole

    How do you handle using native controller things like TempData in your handler classes?

  • https://twitter.com/memark Magnus Markling

    Great article, Jimmy! What are you thoughts on other types of needed web related information, such as the name of the logged in user? Who would extract that from the framework, the controller or the handler?

  • Beyers Cronje

    Great post, thanks Jimmy. One great benefit of this approach that no one has mentioned so far is that it enables the use of the Decorator Pattern http://en.wikipedia.org/wiki/Decorator_pattern to add cross-cutting concerns.

    Steven, aka .NET Junkie, has two posts that goes into more detail on how this is accomplished. I highly recommend anyone interested in this architecture to read Steven’s two posts:

    Meanwhile… on the command side of my architecture – http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=91

    Meanwhile… on the query side of my architecture – http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=92

    Most modern IoC libraries like Simple Injector and Autofac supports decorators, making it a very powerful and clean feature.

  • Allen Firth

    @Jimmy, any idea when you’ll post the POSTs and commands article? I’m really looking forward to that one :-)

  • Eyal Shilony

    First I want to say that I really appreciate your posts.

    I don’t have problems with patterns in fact, I encourage anyone to find
    repetitive code and refactor it as needed but where do you draw the
    line? I mean from this point on all your controllers will probably will
    look almost the same so you can actually write yet another abstraction
    that will eliminate the need for a controller completely, I mean, you
    refactored the code and solved some “issues” that you spotted and that’s
    great but don’t you think that having a mediator is just pushing it?

    Actually, sometimes I want to Read or Write only why even having both Queries and Commands exposed using a mediator? one of the core ideas behind CQRS as I understand it is to separate them so having IQueryDispatcher and ICommandDispatcher seems more logical to me but that’s just based on my personal opinion and materials that I’ve read about it.

    P.S. just an idea, it’s possible to make a base class like hmm CqrsController and expose them using a property rather passing them but that’s design choice.

    The idea of separating them completely is also great when you look at the controller because then you can tell whether this controller is doing Read or Write or both and you don’t get to violate YAGNI or ISP. :)

    Some people agree that the controller should be anemic, I really disagree it should be thin not anemic and really big emphasis on the word should, maybe it should but should it die?

    On the one hand I’m saying awesome your controllers look almost the same which is great (to some extent) and then on the other hand I say to myself (it’s a wonderful world, j/k kidding) what will you do when more controllers will look exactly the same a.k.a duplications? create a new abstraction to eliminate them completely?

    One of the things I dislike about abstractions is that they always make things more complicated to understand and more complex on the software.

    Best regards,

    Eyal Shilony

  • Örjan Sjöholm

    This series of posts i really great and the API is neat but how do you resolve the handler in the mediator. The only thing that I come up with is to use reflection and an IoC like https://gist.github.com/orjan/9179135, but is there better alternatives to create the Mediator?

    • jbogard

      What don’t you like about this approach?

      • Örjan Sjöholm

        It’s mainly my implementation of the Mediator that relies on reflection and manual resolution of the handler, that I’m questioning.

        But it works and the Mediator is really powerful and flexible for cross cutting concerns.

        • jbogard

          I just checked my later version of this and it doesn’t have the reflection stuff in it. Instead, it only depends on an IServiceLocator (from the MS P&P team). I’ll update the post with that.

  • Pingback: SapiensWorks | MvcPowerTools Preview: Query and Command Controllers

  • Dave

    Outstanding Jimmy. I’ve never had the fortune to work with a architect who does this stuff – a REAL architect. It’s great to get to learn from one here!

    • jbogard

      Ha, thanks!

  • http://six.dev-heaven.net Sickboy

    Loving this so far. I wonder though how you deal with accounts / logged-in-user.

    Do you send information about this in your query/command objects, or do you get this information *somewhere* from the system?

    In case in the query/command objects, this would seem insecure if the data is automatically bound from the request uri/querystring parameters etc?
    Or would you ‘secure’ this by custom model binder etc?

    • jbogard

      Good question! I usually have something IUserContext or ISecurityContext. These abstractions are fantastic for those cross-cutting concerns.

      I can be insecure, but I have to rely on the underlying framework to sanitize inputs. It’s not different than normal parameters that I take in, though. What do you do to sanitize inputs?

      • http://six.dev-heaven.net Sickboy

        Thanks for the quick response!

        So far I was not allowing the user to submit such info himself, but instead I would manually insert such information into the query/command object in the controller action.

        I was using a separate input model that was bound in the controller parameters, then I constructed a query or command object that would contain this input model, as well as the additional info I was providing like the logged in user id.

        But when I just re-evaluated your blog again I found you are binding the command/query objects directly in the controller paramters, hence my question :)

        I will probably fiddle some with model binders/formatters, to see how I can accomplish it like your examples, without manual adding additional info in the controller action body :)

        • jbogard

          I wonder, I use validation in my model object too using the Fluent Validation project. Maybe that would help address this scenario? All my validation occurs before the command/query model is sent off to handlers.