How can I dynamically reference an assembly that is looking for another assembly?

Apologies for the tricky question - happy to rephrase if anyone has the best offer.

I am trying to create an object by dynamically invoking an assembly belonging to another application.

The following PowerShell code works well for me:

[Reflection.Assembly]::LoadFrom("C:\Program Files\Vendor\Product\ProductAPI.dll") $bobject = new-object ProductAPI.BasicObject $bobject.AddName("Some Name") 

I am trying to do the same in C #. Based on other posts in StackOverflow, I have this:

 System.Reflection.Assembly myDllAssembly = System.Reflection.Assembly.LoadFile("C:\\Program Files\\Vendor\\Product\\ProductAPI.dll"); System.Type BasicObjectType = myDllAssembly.GetType("ProductAPI.BasicObject"); var basicObjectInstance = Activator.CreateInstance(BasicObjectType); 

The last line throws a TargetInvocationException.

{"Failed to load file or assembly 'AnotherObject, Version = 1.2.345.0, Culture = neutral, PublicKeyToken = null' or one of its dependencies. The system cannot find the specified file."

It looks like the BasicObject constructor is trying to call AnotherObject (from AnotherObject.dll in the same folder), but cannot find it.

Any tips on getting around this?

+6
source share
1 answer

If it cannot find the dependent assembly in ordinary places , you need to manually specify how to find them.

The two easiest ways I know for this are:

  • manually load dependent assemblies in advance Assembly.Load .

  • handles the AssemblyResolve event for the domain that loads the assembly with additional assembly dependencies.

Essentially, you need to know the dependencies for the assembly that you are trying to load in advance, but I don't think such a big question.

If you go to the first option, it would be useful to see the difference between a full load and a reflection of only the download .

If you prefer to use 2 (which I recommend), you can try something like this, which has the additional advantage of working with nested dependency chains (for example, MyLib.dll links, Storyage.dll local resources links, Raven links. Client.dll NewtonSoft.Json.dll), and will also provide you with information about what dependencies it cannot find:

 AppDomain.CurrentDomain.AssemblyResolve += (sender,args) => { // Change this to wherever the additional dependencies are located var dllPath = @"C:\Program Files\Vendor\Product\lib"; var assemblyPath = Path.Combine(dllPath,args.Name.Split(',').First() + ".dll"); if(!File.Exists(assemblyPath)) throw new ReflectionTypeLoadException(new[] {args.GetType()}, new[] {new FileNotFoundException(assemblyPath) }); return Assembly.LoadFrom(assemblyPath); }; 
+7
source

Source: https://habr.com/ru/post/954344/


All Articles