View compilation in ASP.NET 5 with the RazorPreCompileModule

View compilation in ASP.NET 5 with the RazorPreCompileModule

In MVC versions up to and include version 5, you could compile your Razor views by adding the <MvcBuildViews> attribute in the csproj file. But in ASP.NET 5 there is no more csproj file, so how we compile views for MVC 6?

Why?

If you've never compiled views and are wondering why you would, the reason is that it gets you compile-time checking. This means if you change your view model, you'll know if you broke the bindings in your view during compilation of your project. The alternative is waiting until run-time and until you view the page which could easily be overlooked. Sooner is always better.*

How?

The short answer is: Create a class that inherits from RazorPreCompileModule and place it in the {root}\compiler\preprocess** folder of your application.

namespace RazorPrecompileTest.compiler.preprocess
{
    public class RazorPreCompilation : RazorPreCompileModule
    {
    }
}

And that's it! Whenever you build your application your razor views will also be compiled and you'll get compile time checking on them. If you want to know how it works, read on...

So... how does it work?

RazorPreCompileModule

RazorPreCompileModule is an abstract class that implements the assembly neutral interface ICompileModule.

public abstract class RazorPreCompileModule : ICompileModule 

ICompileModule

public interface ICompileModule
{
    void BeforeCompile(BeforeCompileContext context);
    void AfterCompile(AfterCompileContext context);
}

ICompileModule is an interface that "allows plugging into the compilation pipeline". During compilation of your project, dnx will use Roslyn to build up an in memory assembly appended with !preprocess with the same references as your project. It will use that to look for any and all classes that implement ICompileModule and will run the BeforeCompile and AfterCompile methods for each class, before and after compilation, respectively.


*Well, most of the time

**It must be put in that directory!