Using RazorGenerator.Mvc
To consume precompiled views from your Mvc application, you would need to install the RazorGenerator.Mvc
package.
Install-Package RazorGenerator.Mvc
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);
- By default, the
PrecompiledViewEngine
registers itself as the firstViewEngine
to intercept Mvc's calls for View lookups. Consequently, if a virtual path collides with anotherViewEngine
's, then the precompiled engine wins. For example, if your Mvc application and your precompiled application have aView
at~/Home/Index.cshtml
, the precompiled view wins. You can change this behavior by having thePrecompiledMvcEngine
appear later in theViewEngines
list.
ViewEngines.Engines.Add(engine);
- Mvc treats
Layout
files andViewStart
files a bit differently than regularView
files. Their lookup is done via theVirtualPathFactoryManager
. To support this, our view engine implements theIVirtualPathFactory
interface and registers itself duringAppStart
.
// StartPage lookups are done by WebPages.
VirtualPathFactoryManager.RegisterVirtualPathFactory(engine);
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