Compile your asp.net mvc Razor views into a seperate dll

NOTE: THE GENERATOR HAS EVOLVED SINCE THIS POST.Although the post is still worth reading, please go to http://razorgenerator.codeplex.com/ for the most up to date version.

Inspired by David Ebbo‘s blog post ‘Turn your Razor helpers into reusable libraries‘ I wanted to be able to embed compiled Razor views in a dll. This would allow for easy distribution of asp.net mvc ‘modules’ that have their default views embedded, but allowing you to place files in your ‘views’ folder to override those default views.

To generate the c# code for the views, I just started out with David Ebbo’s single file generator and modified it to generate views instead of helpers only. To do this, there had to be a WebRazorHostFactory that knew about all the mvc stuff (what dll’s to reference, what namespaces to use, etc) .I could either choose to include all that information statically in the code, or I could look for a web.config in the same project and let the WebRazorHostFactory use that config. I chose the latter option, so that everyone can easily change the WebRazorHostFactory behavior  by adding a web.config file to their project.

Next, I started figuring out how the PageVirtualPathAttribute inside System.Web.Webpages.dll is used by Microsoft. I found out that it is used when you call ApplicationPart.Register and after that call, there’s not much you can use of this functionality without some heavy reflection. I know it’s the wrong path to choose, but did it anyway. I ended up creating a ViewEngine calling into ApplicationPart’s internal methods to output compiled views. It worked, but I didn’t like it much: there had to be a better way.

I then tried if I could hook into the BuildManager stuff that asp.net mvc uses to generate the views. It was actually much easier then expected, now why didn’t I go on that path the first time!

I ended up creating

  • a CompiledRazorBuildProvider, which inherits from the default RazorBuildProvider,
  • a CompiledVirtualPathProvider which returns a CompiledVirtualFile if it decides that a compiled view should be used
  • and a ApplicationPartRegistry, which registers which compiled views are available.

To view the source, head over to

To just get started without viewing the source, read on, I will explain step by step how to use this library with some screenshots.

If you have improvements, fork the project on GitHub and let me know! If you have suggestions for improvement, just drop it in the comments.

Step 1: Install the FileGenerator

Download and install the Visual Studio extension: http://visualstudiogallery.msdn.microsoft.com/en-us/f28290ce-d987-4f91-b034-707031e10ce6/file/39295/0/RazorSingleFileGenerator.vsix

Step 2: Create new mvc project

image

image

Step 3: Add a class library to hold the views

image

image

Step 4: Cut your Models & Views folders

image

Step 5: Paste them into the just created Class Library

image

Step 6: Copy the website’s web.config file

image

Step 7: Paste that web.config file into the class library

image

Step 8: Select all your .cshtml files in the class library and set the Custom Tool to ‘MvcRazorClassGenerator’

Does anyone have a suggestion on improving this step??

image

Step 9: Build your class library

Step 10: Add your class library to the references of the web application

image

image

Step 11: Add ‘Commons.web.mvc.precompiledviews.dll’ as a reference to your website

this dll is copied to the class library’s output folder (in this case ../EmbeddedViews/bin/debug’)

image

Step 12: Register your views by adding a line to the application_start in global.asax.cs

image

Step 13: Run your website!

Now, you will see the normal default website, even though there aren’t any views in your website path!

If you wish to override some views, just create the normal folders (eg /Views/Home) and add your views there, but don’t forget to copy back the deleted /Views/web.config back into your project then!

6 Replies to “Compile your asp.net mvc Razor views into a seperate dll”

  1. Dear Chris,

    You did an amazing work! We have a legacy project in which we use ASPX engine. I would appreciate it if you could tell me whether we could use this library with ASPX engine?

  2. I have the following view which consists of 3 partial views, two of them need to be passed an object as their model.

    /*************************************************************************************************
    @model sitemap

    @{Html.RenderPartial(“widgets/Header/Skipbar/_Skipnav”); }
    @{Html.RenderPartial(“widgets/Header/Toolbar/_Tools-bar”, thisModel.toolbar); }
    @{Html.RenderPartial(“widgets/Header/Navbar/_Nav-bar”, thisModel.navbar);}

    CS generated code is

    public partial class _Views_Shared_widgets__Header__Header_cshtml : System.Web.Mvc.WebViewPage
    {
    public _Views_Shared_widgets__Header__Header_cshtml()
    {
    }
    public override void Execute()
    {

    #line 5 “..\..\Views\Shared\widgets\_Header\_Header.cshtml”

    sitemap appSitemap = null;

    if (Model == null)
    {

    string siteMapPath = “E:/WorkspacesHoC/HoC/Web/Projects/HOCWB/WebApps/HocCommonElements/HocCommoneElementsViewsLibrary/App_Data/SiteMap.xml”;

    System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(sitemap));
    FileStream file = new FileStream(siteMapPath, FileMode.Open);
    appSitemap = (sitemap)ser.Deserialize(file) as sitemap;
    file.Close();
    }

    var thisModel = (Model != null) ? Model : appSitemap;

    #line default
    #line hidden
    WriteLiteral(“\r\n\r\n\r\n”);

    #line 23 “..\..\Views\Shared\widgets\_Header\_Header.cshtml”

    #line default
    #line hidden

    #line 23 “..\..\Views\Shared\widgets\_Header\_Header.cshtml”
    Html.RenderPartial(“widgets/Header/Skipbar/_Skipnav”);

    #line default
    #line hidden
    WriteLiteral(“\r\n\r\n”);

    #line 25 “..\..\Views\Shared\widgets\_Header\_Header.cshtml”

    #line default
    #line hidden

    #line 25 “..\..\Views\Shared\widgets\_Header\_Header.cshtml”
    Html.RenderPartial(“widgets/Header/Toolbar/_Tools-bar”, thisModel.toolbar);

    #line default
    #line hidden
    WriteLiteral(“\r\n\r\n”);

    #line 27 “..\..\Views\Shared\widgets\_Header\_Header.cshtml”

    #line default
    #line hidden

    #line 27 “..\..\Views\Shared\widgets\_Header\_Header.cshtml”
    Html.RenderPartial(“widgets/Header/Navbar/_Nav-bar”, thisModel.navbar);

    #line default
    #line hidden
    WriteLiteral(“\r\n”);

    }
    }
    }

    }
    }
    }
    **************************************************************************************************/
    The problem is:-
    in my test code, when I do
    var view = new _Views_Shared_widgets__Header__Header_cshtml();
    string output = view.Render();

    output sting does not have the generated partial views, instead it has a GUID for each one of the three partial views (below).

    is there any way to het the three partial views to render so I can have their Markup HTML?
    /**************************************************************************************************

    a3b7048b-14a9-4007-b927-f18f8425459a

    d0a08b90-2731-4b1f-8d0f-0de68488a852

    5f6fdacf-a41d-4649-bd33-ba2f16b14e9a

    **************************************************************************************************/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.