Recently I came across an interesting code illustrating the influence of Just-In-Time (JIT) compilation in .NET on code formation.
Consider the following scenario. A console application refers to some ClassLibrary.dll containing type
The console application in its method
Main() calls method
ClassLibrary.Class1.Echo(). But we want that
ClassLibrary.dll be available to the console application only if the latter has
the appropriate license. The handler of the
event checks this and in case the license is proper returns the required assembly ClassLibrary. Thus, the handler of
event should be called before
ClassLibrary.Class1 instantiation. To test this, we need to build both ClassLibrary.dll and
the console application, then delete
ClassLibrary.dll from the target directory, run the console application, and check whether
event handler (which is the
CurrentDomain_AssemblyResolve() method) is called.
The code below is the console application.
static void Main(string args)
string s = "...";
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
Assembly assm = null;
Console.WriteLine("CurrentDomain_AssemblyResolve is called.");
private static void Echo(string s)
If ClassLibrary.dll was deleted from the target directory then to ensure
the call of the
ASSEMBLY_RESOLVED_CALLED has to be defined. The reason is
as follows. At runtime, the JIT compiler processes every method separately. By the time of this
processing all the required components should be already available. But when
ASSEMBLY_RESOLVED_CALLED is not defined the method
not be processed by the JIT compiler since
ClassLibrary.Class1 is not available.
On the contrary, when
ASSEMBLY_RESOLVED_CALLED is defined
Main() can be processed since it does not contain a direct call
ClassLibrary.Class1, and the
CurrentDomain_AssemblyResolve() method is called.