Precompile your DXA views with Razor Generator

Typically a DXA website solution contains one or more projects containing views, view models, controllers and other logic. For example, a Site project and a module project which contains module views. This way the views are spread over multiple projects. But... ASP.NET MVC does not work with Razor views outside of the website project as explained here [link] and here [link]! Basically Razor views (.cshtml) are not compiled and hence not added to the DLL. Projects referencing to it cannot use the views.
 
Take the DXA example website with the DXA Core module for example. The Site project [link] contains shared views, and the Core module [link] contains entity, region and page views. The DXA example site deals with this by copying over the views from the Core module project to the Site project, in a post-build step.
 
This can be a lot easier: Precompile the views with Razor Generator [link]
 
 
Razor Generator will compile the razor views, making them part of the DLL. This way a single reference from your site project to a module project is enough to use that module including all of its views.
 
Other advantages are that the views are checked for errors at compile time, if anything is off in the views msbuild will complain, without Razor Generator you would not notice until runtime.
 
This is how to set things up.
  1. Open the NuGet Package Manager GUI in Visual Studio
  2. Search for "RazorGenerator"; You will find "RazorGenerator.MsBuild" and "RazorGenerator.Mvc"
  3. Add "RazorGenerator.MsBuild" to all projects containing Razor Views; This will precompile all Razor views.
  4. Add "RazorGenerator.Mvc" to your site project; This will add a RazorGeneratorMvcStart() to the App_Start to make sure the website will use the precompiled views.
  5. Remove duplicate views; If you had copied over any views from a project to your site project, you can remove them from the site project.

 

I hope the DXA Site project and will soon use Razor Generator too [link].