Search code examples
c#.netdependencies.net-assemblyfusion

Why instances created with Activator.CreateInstance do not resolve references?


I have an application with the following folder structure:

Application\Modules\XXX

Of course any assembly inside XXX finds other assemblies inside the XXX.

The problem happens with some instances that are instantiated used reflection:

TProvider providerInstance = (TProvider)Activator.CreateInstance(providerType));

TProvider has a method that returns a class defined in another assembly (stored in XXX as well). When calling that method of the providerInstance that has to load a reference I'm getting a FileNotFoundException about not finding the dependent assembly even when the dependency is in the same XXX folder.

Looking at the fusion log the assembly loader is only checking on the Application folder, not the XXX ...

Any idea on why this happens and how to fix it?

Thanks.


Solution

  • The reason is in that you're loading assembly with LoadFile method:

    LoadFile does not load files into the LoadFrom context, and does not resolve dependencies using the load path, as the LoadFrom method does.

    You should use LoadFrom method and load-from context, or, better, if it is possible, use Load and load context.