Free mag vol1 | Page 698

CHAPTER 17  PROCESSES, APPDOMAINS, AND OBJECT CONTEXTS Let’s add one final method to the current Program class called InitDAD(). As the name suggests, this method will initialize the default application domain, specifically by handling the AssemblyLoad event via a fitting lambda expression. 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); }; } As you would expect, when you run the modified application, you will be notified when a new assembly has been loaded. Here, you are simply printing out the friendly name of the assembly, using the LoadedAssembly property of the incoming AssemblyLoadedEventArgs parameter.  Source Code The DefaultAppDomainApp project is included under the Chapter 17 subdirectory. Creating New Application Domains Recall that a single process is capable of hosting multiple application domains via the static AppDomain.CreateDomain() method. While creating new AppDomains on the fly is a rather infrequent task for most .NET applications, it is important to understand the basics of doing so. For example, as you will see later in this text, when you build dynamic assemblies (see Chapter 18 you will need to install them into a custom AppDomain. As well, several .NET security APIs require you to understand how to construct new AppDomains to isolate assemblies based on supplied security credentials. To investigate how to create new application domains on the fly (and how to load new assemblies into these custom homes), create a new Console Application named CustomAppDomains. The AppDomain.CreateDomain() method has been overloaded a number of times. At minimum, you will specify the friendly name of the new application domain to be constructed. Update your Program class with the following code. Here, you are leveraging the ListAllAssembliesInAppDomain() method from the previous example; however, this time you are passing in the AppDomain object to analyze as an incoming argument. class Program { static void Main(string[] args) { Console.WriteLine("***** Fun with Custom AppDomains *****\n"); // Show all loaded assemblies in default AppDomain. AppDomain defaultAD = AppDomain.CurrentDomain; ListAllAssembliesInAppDomain(defaultAD); 641