Suppose I have a handler for AppDomain.AssemblyResolve
event, and in the handler I construct a byte array and invoke the method Assembly.Load(byte[])
. Can this method itself cause the AssemblyResolve
event to be raised again, and cause my handler to be re-entered?
My question is not restricted only to assemblies that can be generated using C# compiler, they can contain abritrary metadata and executable code supported by the CLR.
I did some experiments and haven't find any cases when it happens. I tried to load assemblies that require additional references, tried to add CAS attributes to the loaded assembly whose decoding would require another assembly, tried to load an assembly with a module initializer (global .cctor
method). In no case I observed the AssemblyResolve
event to be raised from inside the Assembly.Load(byte[])
method, it only happened if some code later tried to access types, methods or attributes in the loaded assembly. But I can be missing something here.
To my knowledge Assembly.Load
or loading assembly by other means does not execute any constructors that can be generated by the C# compiler (including static constructors). As result you're not going to get reentrancy to AssemblyResolve
on commonly found assemblies.
As you've mentioned in the question, module initializers are not executed during the Load
call. Covered in list of guarantees in CLI spec - excerpt can be found in Module Initializers by Junfeng Zhang.
B. The module’s initializer method is executed at, or sometime before, first access to any types, methods, or data defined in the module
There are related SO questions usually discussing "run code before any type constructors" like Initialize library on Assembly load. Note that .Net: Running code when assembly is loaded has an answer by Marc Gravell that states it may not be possible due to security constraints.