Customizing the Microsoft .NET Framework Common Language Runtime
|
The System.AppDomain class has an event called AssemblyLoad that is raised whenever an assembly is loaded into an application domain. AssemblyLoad provides notification when an assembly is loaded, but it doesn't allow you to affect how the assembly is loaded in any way. Note
One scenario in which I find the AssemblyLoad event useful is in debugging. Earlier in the chapter I presented some examples that show how easy it is to load an assembly inadvertently into a different application domain than the one you intended. I've often used the AssemblyLoadEvent to trace all assemblies that get loaded into a process to help diagnose such problems. To register for the AssemblyLoad event, you supply a delegate of type AssemblyLoadEventHandler. Instances of AssemblyLoadEventHandler have the sender and args parameters required by the .NET Framework event model as shown in the following declaration: public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args);
The arguments passed to handlers of AssemblyLoad are of type AssemblyLoadEventArgs. The LoadedAssembly property of AssemblyLoadEventArgs identifies the assembly that has just been loaded. The InitializeNewDomain method of your AppDomainManager class is a convenient place to register your event handler for the AssemblyLoad event. Recall from Chapter 6 that the CLR calls InitializeNewDomain from within each new application domain that is created. Placing your registration code here is a more foolproof way to make sure your handler is attached to all application domains than searching through your code looking for each call to AppDomain.CreateDomain is. The following example creates a new instance of AssemblyLoadEventHandler and registers it for the AssemblyLoad event within InitializeNewDomain. The event handler traces both the identity of the assembly and the friendly name of the application domain into which the assembly was loaded: public class BoatRaceDomainManager : AppDomainManager, IBoatRaceDomainManager { // The event handler for AssemblyLoad static void BoatRaceAssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args) { Trace.WriteLine("Assembly" + args.LoadedAssembly.FullName + " was loaded into" +AppDomain.CurrentDomain.FriendlyName); } public override void InitializeNewDomain(AppDomainSetupappDomainInfo) { // Register a new instance of AssemblyLoadEventHandler to receive the // AssemblyLoad event. AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(BoatRaceAssemblyLoadEventHandler); } }
|
|