Managed assembly loading algorithm
本文内容
Managed assemblies are located and loaded with an algorithm involving various stages.
All managed assemblies except satellite assemblies and WinRT
assemblies use the same algorithm.
When are managed assemblies loaded?
The most common mechanism to trigger a managed assembly load is a static assembly reference. These references are inserted by the compiler whenever code uses a type defined in another assembly. These assemblies are loaded (load-by-name
) as needed by the runtime.
The direct use of specific APIs will also trigger loads:
Algorithm
The following algorithm describes how the runtime loads a managed assembly.
Determine the
active
AssemblyLoadContext.- For a static assembly reference, the
active
AssemblyLoadContext is the instance that loaded the referring assembly. - Preferred APIs make the
active
AssemblyLoadContext explicit. - Other APIs infer the
active
AssemblyLoadContext. For these APIs, the AssemblyLoadContext.CurrentContextualReflectionContext property is used. If its value isnull
, then the inferred AssemblyLoadContext instance is used. - See table above.
- For a static assembly reference, the
For the
Load-by-name
methods, the active AssemblyLoadContext loads the assembly. In priority order by:Checking its
cache-by-name
.Calling the AssemblyLoadContext.Load function.
Checking the AssemblyLoadContext.Default instances' cache and running managed assembly default probing logic.
Raising the AssemblyLoadContext.Resolving event for the active AssemblyLoadContext.
Raising the AppDomain.AssemblyResolve event.
For the other types of loads, the
active
AssemblyLoadContext loads the assembly. In priority order by:Checking its
cache-by-name
.Loading from the specified path or raw assembly object.
In either case, if an assembly is newly loaded, then:
- The AppDomain.AssemblyLoad event is raised.
- A reference is added to the assembly's AssemblyLoadContext instance's
cache-by-name
.
- If the assembly is found, a reference is added as needed to the
active
AssemblyLoadContext instance'scache-by-name
.