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.
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.
LoadFrom(String) Loads an assembly given its file name or path.
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.
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.
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.
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
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