Loading an assembly with recursive references in AppDomain
When loading an assembly into a separate application domain (AppDomain), you also need to manually load its references. Otherwise, a FileNotFoundException error may result due to missing dependencies.
In order to recursively load an assembly and all its references, it is recommended:
<code class="language-C#">// 在当前 AppDomain 中创建一个代理类。 class Proxy : MarshalByRefObject { public Assembly GetAssembly(string assemblyPath) => Assembly.LoadFile(assemblyPath); } // 创建一个新的 AppDomain。 AppDomain domain = AppDomain.CreateDomain("MyDomain", null, domaininfo); // 在新的 AppDomain 中创建一个代理实例。 var value = (Proxy)domain.CreateInstanceAndUnwrap( typeof(Proxy).Assembly.FullName, typeof(Proxy).FullName); // 使用代理将程序集加载到新的 AppDomain 中。 var assembly = value.GetAssembly(assemblyPath); // 迭代程序集的引用并递归加载它们。 foreach (AssemblyName refAsmName in assembly.GetReferencedAssemblies()) { LoadAssemblyWithReferences(refAsmName, domain); }</code>
Use LoadFrom() and LoadFile() to load the assembly
Loading an assembly using LoadFrom() will try to find the assembly in the GAC or the bin folder of the current AppDomain. This operation may fail if the assembly is not in either of these locations.
In contrast, LoadFile() loads an assembly from a specific file path. This method requires you to manually load all dependencies. However, it provides greater control over the assembly loading process.
Following the above steps, the assembly and all its references can be recursively loaded into a separate AppDomain, allowing for a more isolated and controlled execution environment.
The above is the detailed content of How to Recursively Load Assemblies and Their References into a Separate AppDomain?. For more information, please follow other related articles on the PHP Chinese website!