Assembly loading and AppDomain.AssemblyLoad Event
Assembly loading (Assembly.Load) is the process of loading an assembly reference. It starts with an assembly reference, and ends with a System.Reflection.Assembly instance that can be JITted and executed.
Disclaimer:
The following content is implementation detail. It is only applicable to CLR v2.0. And it may change in the future without notice.
The whole loading process can roughly be divided in several phases:
Binding
This is process of locating the file based on the assembly references. MSDN documents the process in detail here (https://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconhowruntimelocatesassemblies.asp).
This phase is performed by fusion.
After binding returns, the file path of the assembly is returned to CLR loader.
Mapping
In this phase the file return from binding is mapped into the process. This is typically accomplished by calling LoadLibrary, and some pre-LoadLibrary and post-LoadLibrary processing.
Deliver Events
CLR Loader delivers profiler and debugger load events for the assembly, and raise AppDomain based events related to assembly load (including AppDomain.AssemblyLoad) event.
Initialize the assembly
Module constructors are run in this phase. Static data are also initialized.
After phase 4, managed code in the assembly can be executed.
As we can see, no managed code can be executed before AppDomain.AssemblyLoad event is delivered. But unmanaged code may run during LoadLibrary if the assembly is MC++ assembly.
Comments
- Anonymous
November 18, 2005
Is there a way for one to create his/her own module constructor? - Anonymous
November 18, 2005
The only way I know is using ILAsm. - Anonymous
January 16, 2006
Is there any way to capture Assembly loading process and provide my own loader (i.e. to load assemblies from database) - Anonymous
January 18, 2006
You can always subscribe AssemblyLoad event and return Assembly.Load(byte[]).
On v2.0 you can use IHostAssemblyManager/IHostAssemblyStore. See MSDN for documentation. - Anonymous
February 10, 2006
In my code I subscribed AssemblyLoad event, but when it is fired, the assembly is already loaded and, for instance, I can not update to the correct assembly... is there an event which happens before the assembly loading? - Anonymous
February 10, 2006
AssemblyLoad event does not return Assembly.Load(byte[]), it is a Sub.
Is there a way to unload the assembly, copy the correct assembly if necessary, and load the correct assembly in AssemblyLoad event? - Anonymous
February 10, 2006
Sorry I had a type in my 1/18 comment. I meant AssemblyResolve event.
No there is no event happens before the assembly loading. No there is no way to unload an assembly.