Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 982
Rudolfs Bundulis Avatar asked Sep 05 '16 16:09

Rudolfs Bundulis


1 Answers

You are right, the compiler deletes the project reference during compilation/optimization, because it detects that it's not really being used by the code.

The official way to tell the runtime to load the assembly anyway by configuration, is to 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>

That being said, sometimes the web.config is not available, or I want to avoid bloating it with more and more lines, so I personally prefer the hack of making a one line reference in the code: (yes, a dirty bad nasty & silly hack, but I can't find much harm being done).

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

A third alternative would be to force the assembly load when the web app starts: (but ensure that your build copies the .dll in your bin\ folder).

Assembly assembly = Assembly.LoadFrom("Newtonsoft.Json.dll");
like image 98
Gerardo Grignoli Avatar answered Oct 25 '22 13:10

Gerardo Grignoli