Welcome to William's ekasi

[ Log On ]
Razor View Engine - Under the Covers
2010/01/01
Tags:

With MVC 3 being released last week (13 Jan 2011) we were given the option of using the new Razor View Engine.  How exactly does the Razor View Engine work?  I’m not talking about the syntax.  I want to know how we go from the razor syntax to the angle brackets for HTML.

1

To start with we have our razor syntax mixed up with HTML markup in a very neat mashup.  And it looks easy enough to convert into, but let’s take a look at the next level down the ASP.Net pipeline to see what happens.

Take a look at the call stack when we put a breakpoint in a Razor view:

2

Start from the System.Web.Mvc.BuildManagerCompiledView.Render(…) up.  The call stack goes from the BuildManagerCompiledView.Render to RazorView.RenderView to a WebPageBase class.  The interesting part of this whole call stack is that the view being rendered subclasses the WebPageBase class.  And it turns out we can change the base class that our views subclass from.  Some more detail found here from K. Scott Allen.

So we know now that our views become classes which subclass either WebViewPage or whatever base class we tell MVC to subclass from.  That still doesn’t explain exactly how the view becomes on of these classes.

Enter three classes:

  • RazorEngineHost
  • RazorTemplateEngine
  • CSharpCodeProvider

Starting from the bottom, the CSharpCodeProvider allows us to take a System.CodeDom.CodeCompileUnit and generate both the C# code and a .Net assembly from it.  To get the CodeCompileUnit that it needs we use the RazorTemplateEngine.

The RazorTemplateEngine allows us to convert the Razor syntax into a CodeCompileUnit by calling the CodeCompileUnit.GenerateCode method.  This method takes a TextReader (8 overloads) and converts that into a CodeCompileUnit.

The RazorEngineHost is used to configure the output of the RazorTemplateEngine.  Using this the namespaces, class names, imports etc are defined.

So the final process of going from a Razor file to a .Net CLR assembly goes like this:

3

And now that we have a CLR assembly of our view we can do some REALLY cool things with it.  The few that really excite me are:

  • Unit test our views (the actual HTML output) WITHOUT needing to instantiate the ASP.Net runtime
  • Put views in a separate assembly and reference them in our web project
  • Use dependency injection to inject controls (or complete views) into views (security personalisation!!!)

If you’re interested in doing a little more of this yourself, Andrew Nurse did a very cool post (and a couple presentations) on how to host Razor outside of the ASP.Net which explains a few details on how to perform the compilation of these views yourself.  I highly recommend going through it.

Add Comment

No comments have been posted yet