SHRI SHRI - 9 months ago 32
C# Question

AssemblyLoad event is not fired in AppDomain

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace DefaultAppDomainApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with the default app domain *****\n");
InitDAD();

DisplayDADStats();
Console.WriteLine();

ListAllAssembliesInAppDomain();

Console.ReadLine();
}

#region Init the default app domain
private static void InitDAD()
{
// This logic will print out the name of any assembly
// loaded into the applicaion domain, after it has been
// created.
AppDomain defaultAD = AppDomain.CurrentDomain;
defaultAD.AssemblyLoad += (o, s) =>
{
Console.WriteLine("{0} has been loaded!", s.LoadedAssembly.GetName().Name);
};
}
#endregion

#region Display basic stats
private static void DisplayDADStats()
{
// Get access to the app domain for the current thread.
AppDomain defaultAD = AppDomain.CurrentDomain;

Console.WriteLine("Name of this domain: {0}", defaultAD.FriendlyName);
Console.WriteLine("ID of domain in this process: {0}", defaultAD.Id);
Console.WriteLine("Is this the default domain?: {0}", defaultAD.IsDefaultAppDomain());
Console.WriteLine("Base directory of this domain: {0}", defaultAD.BaseDirectory);
}
#endregion

#region List loaded assemblies
static void ListAllAssembliesInAppDomain()
{
// Get access to the app domain for the current thread.
AppDomain defaultAD = AppDomain.CurrentDomain;

// Now get all loaded assemblies in the default app domain.
var loadedAssemblies = from a in defaultAD.GetAssemblies() orderby a.GetName().Name select a;

Console.WriteLine("***** Here are the assemblies loaded in {0} *****\n",
defaultAD.FriendlyName);
foreach (var a in loadedAssemblies)
{
Console.WriteLine("-> Name: {0}", a.GetName().Name);
Console.WriteLine("-> Version: {0}\n", a.GetName().Version);
}
}
#endregion

}
}


The above code I got from "Pro C# 2010 and the .NET 4 Platform" book by 'Andrew Troelsen'.
Here when I run this code, the control never reaches the line

defaultAD.AssemblyLoad += (o, s) =>
{
Console.WriteLine("{0} has been loaded!", s.LoadedAssembly.GetName().Name);
};


Why this event is not fired when I run this code? When the control reaches here?

Answer Source

From the documentation (and what I have experienced), the event only fires when one of the Assembly.Load methods are used.

It will not fire when the runtime resolves and loads an assembly automatically.