To consume precompiled views from your Mvc application, you would need to install the RazorGenerator.Mvc package.

Install-Package RazorGenerator.Mvc

How it works

Views generated by the precompiled views contain a PageVirtualPath attribute that records the VirtualPath they correspond to. These values are constructed from the relative paths of the cshtml files under the Views directory.
The package adds a pre-application start hook via the type RazorGeneratorMvcStart to include a ViewEngine to the Mvc's list of engines.

var engine = new PrecompiledMvcEngine(typeof(RazorGeneratorMvcStart).Assembly) 
    UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal

ViewEngines.Engines.Insert(0, engine);

Configuring the PrecompiledMvcEngine

  • By default, the PrecompiledViewEngine registers itself as the first ViewEngine to intercept Mvc's calls for View lookups. Consequently, if a virtual path collides with another ViewEngine's, then the precompiled engine wins. For example, if your Mvc application and your precompiled application have a View at ~/Home/Index.cshtml, the precompiled view wins. You can change this behavior by having the PrecompiledMvcEngine appear later in the ViewEngines list.


  • Mvc treats Layout files and ViewStart files a bit differently than regular View files. Their lookup is done via the VirtualPathFactoryManager. To support this, our view engine implements the IVirtualPathFactory interface and registers itself during AppStart.

    // StartPage lookups are done by WebPages. 

Unlike the ViewEngine scenario, we choose to do the opposite with Layout and ViewStart files: if the path of a _ViewStart file or a Layout file exists both in your precompiled assembly and your Mvc application, we'll choose the one in your Mvc application.

You can change this behavior by setting the PreemptPhysicalFiles to true on your engine:

engine.PreemptPhysicalFiles = true;

  • To facilitate a simpler design time experience, the ViewEngine uses physical files if they are newer than the precompiled assembly. This is to avoid having to rebuild your assembly every time you make changes to your view file. You can turn off this behavior (or make it more complex), by changing this line of code:

UsePhysicalViewsIfNewer = HttpContext.Current.Request.IsLocal

Last edited Nov 12, 2012 at 3:31 PM by pranavkm, version 4


No comments yet.