Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection.Net: how to load dependencies?

I try to add an addons system to my Windows.Net application using Reflection; but it fails when there is addon with dependencie.

Addon class have to implement an interface 'IAddon' and to have an empty constructor.
Main program load the addon using Reflection:

Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\Addon.dll"); Type t = assembly.GetType("Test.MyAddon"); ConstructorInfo ctor = t.GetConstructor(new Type[] { }); IAddon addon= (IAddon) ctor.Invoke(new object[] { }); addon.StartAddon(); 

It works great when addon do not use dependencie. But if my addon reference and use an another DLL (C:\Temp\TestAddon\MyTools.dll) that is saved near the addon in disk, it fails:
System.IO.FileNotFoundException: Could not load file or assembly 'MyTools.dll' or one of its dependencies.

I do not wants to copy the addons DLL near my executable, how can i do to tell .Net runtime to search in "C:\Temp\TestAddon\" for any dependency?

Note that adding

Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\MyTools.dll"); 

do not change anything.

like image 440
Olivier de Rivoyre Avatar asked Oct 08 '08 09:10

Olivier de Rivoyre


People also ask

Could not load the file or assembly or one of its dependencies?

In summary if you get the "Could not load file or assembly error", this means that either your projects or their references were built with a reference to a specific version of an assembly which is missing from your bin directory or GAC.

What is the method used to load assembly by specifying filename?

LoadFrom(String) Loads an assembly given its file name or path.

Can only be loaded in the reflection only loader context?

The reflection-only load context allows you to examine assemblies compiled for other platforms or for other versions of the . NET Framework. Code loaded into this context can only be examined; it cannot be executed. This means that objects cannot be created, because constructors cannot be executed.

What is Assembly reflection?

Assembly Class. Assembly: Mscorlib.dll. Namespace: System.Reflection. Summary. Defines an Assembly, which is a reusable, versionable, and self-describing building block of a common language runtime application.


2 Answers

If MyTools.dll is located in the same directory as Addon.dll, all you need to do is call Assembly.LoadFrom instead of Assembly.LoadFile to make your code work. Otherwise, handling the AppDomain.AssemblyResolve event is the way to go.

like image 107
Andreas Tschager Avatar answered Sep 22 '22 10:09

Andreas Tschager


Have you looked into using an Inversion Of Control container? I use Castle Windsor with an external Boo file that lets me easily extend the applcation without having to recompile or worry about supplying dependencies

like image 22
Chris Canal Avatar answered Sep 25 '22 10:09

Chris Canal