Transitioning to Managed Hosting Code
After loading and initializing the runtime, the host must make the transition from unmanaged to managed code in order to execute managed hosting code and user code. The managed hosting code is usually run in the default application domain. The default application domain is created automatically by the runtime every time it is initialized. When the process shuts down, the default application domain is unloaded. Most hosts do not run user code in the default application domain because it cannot be shut down independently of the process.
To make the transition to managed code, the host must obtain a pointer to the default application domain and then load the managed portion of the host into that domain. After the transition to managed code is complete, the managed portion of the host can create additional application domains in which to locate user code or more hosting code. For more information, see Creating and Configuring Application Domains.
A host can obtain an interface pointer to the default application domain by calling ICorRuntimeHost::GetDefaultDomain. The call returns a pointer to the instance of System.AppDomain that represents the default application domain. The interface pointer is of type _AppDomain. In short, the host calls methods on an instance of the managed class System.AppDomain through COM interoperability services to load the managed hosting code into the default domain. After the host obtains a pointer to the default domain, you can call one of the Load methods on System.AppDomain to load the managed portion of the host into the default domain.
The managed portion of the host typically contains most of the host's logic. When the transition to managed code is complete, the unmanaged hosting code is no longer required. Because the user code that the host loads and runs is all managed, implementing the majority of the host in managed code provides better performance. Performance is better because calls from the hosting code to the user code are all done in the managed environment instead of moving back and forth from unmanaged code to managed code each time the host and user code interact.