Weird behavior when mixing loading of assemblies using Assembly.LoadFrom and Assembly.Load
I have encountered a weird behavior when loading assemblies with Assembly.
@Kent Boogart: That appears to be the correct explanation. For a full explanation, Suzanne Cook has this blog post which elaborates a little more than the original one you posted: http://blogs.msdn.com/suzcook/archive/2003/05/29/57143.aspx
Following is code leveraging AppDomain.AssemblyResolve -
// register to listen to all assembly resolving attempts:
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
// Check whether the desired assembly is already loaded
private static Assembly MyResolveEventHandler(object sender, ResolveEventArgs args) {
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
foreach (Assembly assembly in assemblies) {
AssemblyName assemblyName = assembly.GetName();
string desiredAssmebly = args.Name;
if (assemblyName.FullName == desiredAssmebly) {
return assembly;
}
}
// Failed to find the desired assembly
return null;
}
That's not weird. As per the documentation, loading with Load and LoadFrom will place the assemblies in different contexts. This might help.
- Any explanation why the CLR ignores the already loaded assembly?
Because they're in a different context.
- Any idea how can I alleviate this problem?
Load from the same context, or help the CLR find the assembly, perhaps by attaching a handler to AppDomain.AssemblyResolve
.
Alternative
If the location you are loading assemblies from is a subfolder under AppDomain.BaseDirectory you can simply add an entry to your App.config:
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="bin;bin2\subbin;bin3"/>
</assemblyBinding>
</runtime>
</configuration>
http://msdn.microsoft.com/en-us/library/823z9h8w.aspx