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

598 views Asked by At

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

1

There are 1 answers

1
RB. On

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.