Home >Backend Development >C++ >How to Recursively Load Assemblies and Their References in a New AppDomain?

How to Recursively Load Assemblies and Their References in a New AppDomain?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-15 12:07:44583browse

How to Recursively Load Assemblies and Their References in a New AppDomain?

Recursively load the assembly and all its references in a new AppDomain

In order to load an assembly into a new AppDomain and recursively load all its references, follow these steps:

1. Create a proxy class in AppDomain:

<code class="language-csharp">public class Proxy : MarshalByRefObject
{
    public Assembly GetAssembly(string assemblyPath)
    {
        try
        {
            return Assembly.LoadFile(assemblyPath);
        }
        catch (Exception ex)
        {
            //  记录异常信息以便调试
            Console.WriteLine($"加载程序集失败: {ex.Message}");
            return null;
        }
    }
}</code>

2. Create AppDomain and domain proxy:

<code class="language-csharp">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);
Proxy value = (Proxy)domain.CreateInstanceAndUnwrap(
    type.Assembly.FullName,
    type.FullName);</code>

3. Load root assembly:

<code class="language-csharp">string path = System.IO.Path.Combine(dir, "MyDll.dll");

Assembly assembly = value.GetAssembly(path);</code>

By using the CreateInstanceAndUnwrap method, the proxy object will be executed in a new AppDomain and the assembly and all its dependencies will be loaded recursively. Note that you need to use LoadFile instead of LoadFrom to avoid the dependency resolution issues mentioned in the question. The improved code includes exception handling to better handle errors that may occur while loading an assembly.

The above is the detailed content of How to Recursively Load Assemblies and Their References in a New AppDomain?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn