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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With