简体   繁体   中英

Why is AssemblyResolve event trying to resolve an assembly that is already loaded in the AppDomain?

I have a service that involves downloading an assembly from cloud storage, creating an instance of it using Activator.CreateInstance and then invoking a method on it.

I have set up a AssemblyResolve method to download dependencies which works fine, but to test/experiment I am now trying to manually download assemblies. I have got as far as finding which dependencies are needed, downloading them and then loading them using

Assembly.Load(byte[])

After which I can see they are loaded into the AppDomain via

AppDomain.CurrentDomain.GetAssemblies())

However when I am invoking the method on the assembly which references this, it still goes to the AssemblyResolver.

I may be misunderstanding how loaded assemblies and the AppDomain works but it seems to me that once the assembly is loaded it should be available to this assembly and it shouldn't need to resolve it?

Why can't it "see" it? The version and name etc is the same.

I have read about the different assembly binding contexts here and I think this could be the issue? It suggests that using Assembly.Load(string) will load to a different context than Assembly.Load(byte)? In which case how do I do this when I just have the assembly in memory as a byte[]?

Thanks

You need to obtain the Type directly from the assembly you loaded, as it is not loaded into the correct context.

var assembly = Assembly.Load(File.ReadAllBytes(some_path));

// This will work. Note that you don't need the assembly-qualified name,
// as you are asking the assembly directly for the type.
var type1 = assembly.GetType("My.Special.Type");

// This will not work - the assembly "My.Assembly" is not loaded into
// the Load context, so the type is not available.
var type2 = Type.GetType("My.Special.Type, My.Assembly");

In the code above, type1 will have a reference to the Type, but type2 will be null, as the assembly is not loaded into the normal Load context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM