2013-07-26 22 views
2

我想調用一個類在單獨的AppDomain下運行,但我收到了關於能否加載該類或其某個依賴項的異常。這是我正在做的一個例子。如何在AppDomain下創建類的新實例

AppDomain ad = AppDomain.CreateDomain("New domain"); 
IIdentity identity = new GenericIdentity("NewUser"); 
IPrincipal principal = new GenericPrincipal(identity, null); 
ad.SetThreadPrincipal(principal); 
TestClass remoteWorker = (TestClass)ad.CreateInstanceAndUnwrap(
         binFolder+"\\TestProject.dll", 
         "TestClass"); 
remoteWorker.Run(data1,data2); 

在我單獨TestProject我有一個名爲類的TestClass:

public class TestClass : MarshalByRefObject 
{ 
     public void Run(string name, string path) 
     { 
      //Some stuff 
     } 
    } 

我已經檢查的所有路徑的一切,他們是正確的。我得到的錯誤:

Could not load file or assembly 'K:\\Installer\\Bin\\TestProject.dll' 
or one of its dependencies. The given assembly name or codebase was invalid. 
(Exception from HRESULT: 0x80131047) 

我試過改變路徑,將其移動到當前正在執行的程序集。依然沒有。該DLL位於K:\ Installer \ Bin \ TestProject.dll中。我在管理員下運行它,因此它具有對Dll的權限。

+0

您是否試圖捕獲ReflectionTypeLoadException異常?也許「TestProject.dll」有一些運行時無法解決的依賴項。 – McGarnagle

+0

包含中唯一的是系統Dlll。那些如何解決? – busbina

回答

1

想通了。將我的代碼更改爲:

AppDomainSetup domainSetup = new AppDomainSetup 
          {PrivateBinPath = binFolder+"\\TestProject.dll"}; 
AppDomain ad = AppDomain.CreateDomain("New domain",null, domainSetup); 

TestClass remoteWorker = (TestClass)ad.CreateInstanceFromAndUnwrap(
          binFolder+"\\TestProject.dll", 
          typeof(TestClass).FullName); 
相關問題