Recursively load the assembly and its references in a standalone AppDomain
When loading an assembly into a new AppDomain, be sure to load all of its references recursively to prevent FileNotFoundException
errors. This article explores the steps to accomplish this complex task.
First, create a standalone AppDomain with a custom ApplicationBase
. Then, use AssemblyName.GetAssemblyName
to load the root assembly. However, this alone is not enough; you need to manually load the assembly's reference.
To do this, use ReflectionOnlyLoadFrom
to get a list of referenced assemblies without actually loading them. For each reference, use domain.Load(refAsmName)
to load it into the AppDomain.
However, there is a caveat here. To execute a proxy object in an external application domain, you need to call CreateInstanceAndUnwrap
. This method ensures that the object executes in the target AppDomain.
Code example illustrating this process:
<code class="language-csharp">class Program { static void Main(string[] args) { AppDomainSetup domaininfo = new AppDomainSetup(); domaininfo.ApplicationBase = System.Environment.CurrentDirectory; Evidence adevidence = AppDomain.CurrentDomain.Evidence; AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo); Type type = typeof(Proxy); var value = (Proxy)domain.CreateInstanceAndUnwrap( type.Assembly.FullName, type.FullName); var assembly = value.GetAssembly(args[0]); // AppDomain.Unload(domain); } } public class Proxy : MarshalByRefObject { public Assembly GetAssembly(string assemblyPath) { try { return Assembly.LoadFile(assemblyPath); } catch (Exception) { return null; // throw new InvalidOperationException(ex); } } }</code>
Remember that when using LoadFile
instead of LoadFrom
you must load any dependencies yourself to avoid FileNotFound
exceptions.
The above is the detailed content of How to Recursively Load Assembly References into a Separate AppDomain?. For more information, please follow other related articles on the PHP Chinese website!