Using C#, I create a DLL at runtime and now I want to add it as a reference to my project at runtime.
I tried using the LoadFrom
method, but it doesn't work.
How can I do this?
A DLL is a library that contains code and data that can be used by more than one program at the same time. For example, in Windows operating systems, the Comdlg32 DLL performs common dialog box related functions. Each program can use the functionality that is contained in this DLL to implement an Open dialog box.
First you should load the dll
Assembly assembly = Assembly.LoadFrom("dllPath");
Then you may need to add the assembly to the app domain
AppDomain.CurrentDomain.Load(assembly.GetName());
After that you can load any type from this assembly
Type t = assembly.GetType("typeName");
Then using reflection you can execute methods on this type
Note that you may need to add the below in the configuration file.
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="dlls folder"/>
</assemblyBinding>
</runtime>
LoadFile vs. LoadFrom
Be careful - these aren't the same thing.
LoadFrom() goes through Fusion and can be redirected to another assembly at a different path but with that same identity if one is already loaded in the LoadFrom context. LoadFile() doesn't bind through Fusion at all - the loader just goes ahead and loads exactly* what the caller requested. It doesn't use either the Load or the LoadFrom context. So, LoadFrom() usually gives you what you asked for, but not necessarily. LoadFile() is for those who really, really want exactly what is requested. (*However, starting in v2, policy will be applied to both LoadFrom() and LoadFile(), so LoadFile() won't necessarily be exactly what was requested. Also, starting in v2, if an assembly with its identity is in the GAC, the GAC copy will be used instead. Use ReflectionOnlyLoadFrom() to load exactly what you want - but, note that assemblies loaded that way can't be executed.)
LoadFile() has a catch. Since it doesn't use a binding context, its dependencies aren't automatically found in its directory. If they aren't available in the Load context, you would have to subscribe to the AssemblyResolve event in order to bind to them.
ref Suzanne Cook's .NET CLR Notes
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