簡體   English   中英

創建自定義AppDomain並向其添加程序集

[英]Create custom AppDomain and add assemblies to it

如何創建appdomain,向其添加程序集,然后銷毀該app域? 這是我嘗試過的:

    static void Main(string[] args)
    {           
        string pathToExe = @"A:\Users\Tono\Desktop\ConsoleApplication1.exe";

        AppDomain myDomain = AppDomain.CreateDomain("MyDomain");

        Assembly a = Assembly.Load(System.IO.File.ReadAllBytes(pathToExe));

        myDomain.Load(a.FullName); // Crashes here!            
    }

我也嘗試過:

myDomain.Load(File.ReadAllBytes(pathToExe)); 

如何將程序集添加到appdomain。 一旦我這樣做,我可以通過反射找到方法執行它,然后銷毀appdomain

我得到的例外是:

無法加載文件或程序集“ConsoleApplication1,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null”或其依賴項之一。 該系統找不到指定的文件。

兩個快點:

  1. AppDomain.Load在當前AppDomain.Load加載程序集而不在myDomain上加載(很奇怪,我知道)。
  2. AppDomain.LoadLoad上下文中加載一個程序集,該上下文從apps base-dir,private-bin-paths和GAC中解析程序集。 最有可能的是,您嘗試加載的程序集不在任何這些解釋異常消息的位置。

有關更多信息,請查看此答案

將程序集加載到AppDomain的一種方法是創建MarshalByRef派生的加載程序。 您需要這樣的東西,以避免泄漏類型(和程序集)到您的主AppDomain。 這是一個簡單的:

public class SimpleAssemblyLoader : MarshalByRefObject
{
    public void Load(string path)
    {
        ValidatePath(path);

        Assembly.Load(path);
    }

    public void LoadFrom(string path)
    {
        ValidatePath(path);

        Assembly.LoadFrom(path);
    }

    private void ValidatePath(string path)
    {
        if (path == null) throw new ArgumentNullException("path");
        if (!System.IO.File.Exists(path))
            throw new ArgumentException(String.Format("path \"{0}\" does not exist", path));
    }
}

並使用它:

//Create the loader (a proxy).
var assemblyLoader =  (SimpleAssemblyLoader)myDomain.CreateInstanceAndUnwrap(typeof(SimpleAssemblyLoader).Assembly.FullName, typeof(SimpleAssemblyLoader).FullName);
//Load an assembly in the LoadFrom context. Note that the Load context will
//not work unless you correctly set the AppDomain base-dir and private-bin-paths.
assemblyLoader.LoadFrom(pathToExe);

//Do whatever you want to do.

//Finally unload the AppDomain.
AppDomain.Unload(myDomain);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM