Sunday, June 7, 2009

ASP.Net MVC Pipeline – Part 1

This is Part 1 of a series of posts I hope to write exploring the Asp.Net MVC pipeline. It won’t be your typical “this is a view, this is a controller, right click add new item…” type series although it will start off fairly basic and I will attempt to simplify things where necessary.

I’ll also be exploring some best practice and testing concerns along the way.

Pipeline 101

When I talk about the pipeline, I’ll mostly be talking about the stuff that happens OUTSIDE of your views, models and controllers. You might be wondering why you would want to do that? Well Asp.Net provides quite an array of conventions that can be overridden by the developer. Ever wondered how on earth you can specify an action to receive a populated instance of one of your domain classes? Well these “extensibility points” points allow you to change this type of behaviour.

Our First Request

First Request

Like I said, I was going to simplify things :) Anyone who’s had a cursory glance at Asp.Net MVC should be able to understand what’s going on here. I won’t go into great detail for each step but there are a few things I’d like to point out.

If we look at the controller action definition, it is simply:

Other than the method name, nowhere does it specify what view to actually use. We can verify this with the following test which will fail in this scenario

So how does the pipeline know to render the view at “~/Views/Account/Index.aspx”? Well that’s a convention of the default MVC pipeline that we can extend and control as we see fit.

This also means that the controller action and view are not tightly bound too each other. The action cares not what happens with the action result it returns nor does the view care which action its data comes from. In this way we can even replace entire parts of the pipeline e.g alternate view engines.

This separation really sets MVC apart from webforms and allows for much easier testing. Despite their appearances controllers and views can still “Do Bad Things” like make calls to Response.Redirect(…) etc. Generally from upon though :)

In Part 2 we’ll be examining probably the easiest way to manipulate the pipeline: Routes!

No comments:

Post a Comment