2013-01-02 20 views
6

我正在從一個新的AppDomain中的特定「擴展」目錄加載所有DLL,以獲取與這些相關的一些反射信息。接收來自另一個AppDomain的程序集引用的異常

這就是我想:

我創造了我的解決方案一個新的圖書館AssemblyProxy這只是有這個類:

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

我要確保這個DLL出現在我的「擴展」目錄。然後,我使用下面的代碼將「extensions」目錄下的所有程序集加載到新的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是否嘗試在接收引用時自行加載程序集?

謝謝。

+4

你試過了什麼? –

+0

是否[[ReflectionOoadOnly'](http://msdn.microsoft.com/zh-cn/library/ms172331(v = vs.100).aspx)足以滿足您的(未知)目的? –

+0

[CreateInstanceAndUnwrap](http://msdn.microsoft.com/en-us/library/system.appdomain.createinstancefromandunwrap.aspx)有什麼問題? – Algirdas

回答

2

你不應該返回從新AppDomainAssembly對象,因爲如果你主要AppDomain訪問它不會因爲程序集位於一個目錄中的組件,這隻會工作:

指定的目錄爲了避免這種

的一種方式遵循leppie的評論和:

  1. 創建一個序列化的類型,包括您從Assembly對象所需要的最低限度的信息。
  2. 將此類型添加到AppDomain都可以訪問的新程序集中。通過將其添加到GAC來完成此操作的最簡單方法。

另一種方法是使用Mono.Cecil而不是System.Reflection。 Mono.Cecil將允許您檢查程序集而不加載它們。從這個answer的下半部分看一個非常簡單的例子。

+0

你確定'Assembly'對象有問題嗎?因爲如果我使用'ReflectionOnlyLoadFrom',那麼相同'Assembly'類型的對象引用會成功返回。 – user1004959

+0

@ user1004959我確信返回Assembly對象不是你應該做的。也許特定的程序集已經被加載到主AppDomain。添加一個斷點在foreach的最後一行,運行該程序,然後使用Visual Studio的快速監視功能,並評估System.AppDomain.CurrentDomain.GetAssemblies()。如果你可以看到加載的程序集,那麼它以某種方式加載到你的主AppDomain。試驗過程中,您有沒有機會訂閱AssemblyResolve活動? –

相關問題