簡體   English   中英

從另一個AppDomain接收程序集引用時發生異常

[英]Exception on receiving Assembly reference from another AppDomain

我正在從新AppDomain中特定“擴展名”目錄中加載所有DLL,以從中獲取一些與反射相關的信息。

這是我正在嘗試的:

我在解決方案中創建了一個新的庫AssemblyProxy ,該庫僅包含此類:

public class AssemblyProxy : MarshalByRefObject
{
    public Assembly LoadFile( string assemblyPath )
    {
      try
      {
        return Assembly.LoadFile( assemblyPath );
      }
      catch
      {
        return null;
      }
    }
}

我確保此DLL位於我的“擴展名”目錄中。 然后,我使用以下代碼將“擴展名”目錄中的所有程序集加載到新的AppDomain

foreach( string extensionFile in Directory.GetFiles( ExtensionsDirectory, "*.dll" ) )
{
        Type type = typeof( AssemblyProxy.AssemblyProxy );
        var value = (AssemblyProxy.AssemblyProxy) Domain.CreateInstanceAndUnwrap(
            type.Assembly.FullName,
            type.FullName );

        var extensionAssembly = value.LoadFile( extensionFile );

        types.AddRange( extensionAssembly.GetTypes() );
}

某些DLL確實可以成功加載,但是在某些DLL上會引發如下異常:

Could not load file or assembly 'Drivers, Version=2.3.0.77, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

編輯:在新的AppDomain中不會引發異常。 DLL已成功加載到新的AppDomain中。 程序集引用返回到主/調用AppDomain后,立即引發該異常。 主/調用AppDomain是否僅在收到引用時嘗試自行加載程序集?

謝謝。

您不應該從新的AppDomain返回一個Assembly對象,因為只有主AppDomain可以訪問那些不可以訪問的程序集時,這才起作用,因為這些程序集位於以下目錄中:

避免這種情況的一種方法是遵循嬉皮士的評論,並:

  1. 創建一個序列化類型,其中包括您需要從Assembly對象獲取的最少信息。
  2. 將此類型添加到兩個AppDomain都可以訪問的新程序集中。 將其添加到GAC的最簡單方法。

另一種方法是使用Mono.Cecil代替System.Reflection Mono.Cecil將允許您檢查裝配而無需加載它們。 作為一個非常簡單的示例,請看此答案的后半部分。

暫無
暫無

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

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