Rudolfs Bundulis Rudolfs Bundulis - 3 months ago 7
C# Question

Force C# to load an assembly that is referenced only in a cshtml file

How to force C# run-time to load an assembly that is used only in a

.cshtml
file which is a Razor template?

I am using the JSON serialization functionality from
Newtonsoft
, the assembly is referenced by the project, but when the Razor engine compiles the template I get an error that the
Newtonsoft
namespace is not known. I also see that the dll is actually not loaded (I guess it makes sense since it is not referenced anywhere in the C# code). If I add a dummy line somewhere in my C# code that references any function from the assembly it is loaded and Razor is happy. Is there a way to specify that the assembly should be loaded even though it is not referenced? I really don't want to leave the dummy line in the code.

Answer

Option 1 - Make a reference in the code:

class LoadNewtonSoftHack
{
    private void DoNothing()
    {
        var o = Newtonsoft.Json.Linq.JValue.Parse("{}");
    }
}

Option 2 - Load using reflection:

Assembly assembly = Assembly.LoadFrom("Newtonsoft.Json.dll");

Option 3 - Add a reference in your web.config file inside the <compilation> section

<compilation debug="true" targetFramework="4.0">
  <assemblies>
    <add assembly="Newtonsoft.Json" />
  </assemblies>
</compilation>