Compiling RazorEngine views at build time

Apr 17, 2014 at 6:55 PM
Thought I'd share this, as it may be of use to someone else.

I have an email notification project that uses RazorEngine to generate email content. All of my templates and fragments are kept in a collection of .cshtml files in my project. Through posts I'd found elsewhere, I'd been able to get Intellisense working, but Intellisense will only complain about errors while the file is open in VS. No good for our build server.

In ASP.NET projects, building views at compile time is triggered through a <Aspnetcompiler> task in the project file. To do the same for my email notifier, I added the following under <PropertySettings> for my 'Release' configuration:
I then skipped down to the bottom of my .csproj file and found the 'AfterBuild' target, which I replaced with the following:
<Target Name="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
    <AspNetCompiler VirtualPath="temp" PhysicalPath="$(ProjectDir)\..\$(ProjectName)" />
Great! Now I was getting build errors for broken views. Unfortunately for me, this introduced another problem. All of my views inherit from RazorEngine.Templating.TemplateBase<T>. The classes that the ASP.NET compiler auto-generates assume that each view is going to be a System.Web.Mvc.WebViewPage, and contain references to the 'Context' property for that class. This caused additional build errors to pop up when I compiled. To get around this, I created a new base class to use for templating:
using System;
using System.Web;
using RazorEngine.Templating;

namespace My.Notifications
    public class MyTemplateBase<T> : TemplateBase<T>
        public HttpContextBase Context { get; set; }
Voila. Happy builds.