RazorEngine – Referenced assemblies are not loaded if only consumed in a view-Collection of common programming errors

I’m using RazorEngine to perform some templating in a service layer, outside of the context of MVC and I’m having problems with assemblies not being loaded into the AppDomain when the classes in those assemblies are used only in the views. Let me elaborate.

I have some Razor templates that are embedded resources in a standalone assembly (let’s call it Assembly A).

One of the templates (MyTemplate) consumes a utility class (MyHelperClass) which resides in another assembly (let’s call it Assembly B).

Assembly A has a hard reference to Assembly B.

When I try to parse the template that references MyHelperClass I get the familiar, “are you missing a using directive or an assembly namespace”. When I debug and look at the modules window in Visual Studio I can see that Assembly B is not loaded into the AppDomain. If I debug through the code and load the assembly via the intermediate window before the failing line of code, it works.

So, it seems that merely being consumed in a view isn’t enough for the .NET framework to load an assembly into the AppDomain. I assume this may well be the case in a standard MVC project as well, although I haven’t tested this.

Two questions really.

  1. Is a reference in a view not enough to cause the runtime to load an assembly?
  2. In this situation, what’s the best way to force this assembly to load without having to resort to Assembly.Load or referencing a dummy class.
  1. Declare the namespace of MyHelperClass in web.config:

    
      
    
    
      
        
      
    
    
  2. In the end I decided that runtime compilation for these templates was just too fragile and the possibility of having this crop up in the future made me feel very uneasy. Instead I decided to change my project to use the RazorGenerator NuGet package and have the views precompiled to avoid any runtime surprises.