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:

 

  1. 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.

  2. 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.

  3. 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.

  4. 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.