19.8. Running Code in Its Own AppDomain
Problem
You want to run code isolated from the main part of your application.
Solution
Create a separate AppDomain to run the code using the AppDomain.CreateDomain method. CreateDomain allows the application to control many aspects of the AppDomain being created like the security environment, the AppDomain settings, and base paths for the AppDomain. To demonstrate this, the code creates an instance of the RunMe class (shown in full later in this recipe) and calls the PrintCurrentAppDomainName method. This prints the name of the AppDomain where the code is running:
public static void RunCodeInNewAppDomain()
{
AppDomain myOwnAppDomain = AppDomain.CreateDomain("MyOwnAppDomain");
// Print out our current AppDomain name.
RunMe rm = new RunMe();
rm.PrintCurrentAppDomainName();Now, you create an instance of the RunMe class in the "MyOwnAppDomain" AppDomain by calling CreateInstance on the AppDomain. We pass CreateInstance the module and type information necessary for constructing the type, and it returns an ObjectHandle.
We can then retrieve a proxy to the instance running in the AppDomain by taking the returned ObjectHandle and casting it to a RunMe reference using the Unwrap method:
// Create our RunMe class in the new AppDomain. Type adType = typeof(RunMe); ObjectHandle objHdl = myOwnAppDomain.CreateInstance(adType.Module.Assembly.FullName, adType.FullName); // Unwrap the reference. RunMe adRunMe = (RunMe)objHdl.Unwrap();
The PrintCurrentAppDomainName ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access