2011-06-09 90 views
2

我努力做到以下幾點:試圖創建實例應用領域

private static MyClass CreateMyClassInDomain(ApplicationDomain domain, string componentName, params object[] parmeters) 
{ 
    var componentPath = Assembly.GetAssembly(typeof(MyClass)).CodeBase.Substring(8).Replace("/", @"\"); 
    ObjectHandle inst = Activator.CreateInstanceFrom(domain, componentPath, "MyNsp." + componentName, true, BindingFlags.Default, null, 
      parmeters, null, null); 

    return (MyClass)inst.Unwrap(); 
} 

有什麼我做錯了什麼?我創建成功,但之後當我嘗試使用MyClass的實例在某些情況下,我有意外的異常。

編輯: 找到了問題的根源,我一直在使用的DLL,我在當前的應用程序域 加載到從其他應用程序域創建實例,並將其造成的不一致性

謝謝。

+2

什麼是例外?你期望什麼異常? :) – Simone 2011-06-09 11:00:19

+2

什麼是意外異常? – leppie 2011-06-09 11:00:27

回答

1

檢查示例代碼以加載不同域中的對象並執行工作。

如果應用程序中引用了該組件dll,則只能將該對象加載到不同的對象中。

如果它沒有被引用,然後去反思。

namespace MyAppDomain 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      // Create an ordinary instance in the current AppDomain 
      Worker localWorker = new Worker(); 
      localWorker.PrintDomain(); 

      // Create a new application domain, create an instance 
      // of Worker in the application domain, and execute code 
      // there. 
      AppDomain ad = AppDomain.CreateDomain("New domain"); 
      ad.DomainUnload += ad_DomainUnload; 
      //ad.ExecuteAssembly("CustomSerialization.exe"); 

      Worker remoteWorker = (Worker)ad.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "MyAppDomain.Worker"); 

      remoteWorker.PrintDomain(); 

      AppDomain.Unload(ad); 
     } 


     static void ad_DomainUnload(object sender, EventArgs e) 
     { 
      Console.WriteLine("unloaded, press Enter"); 
     } 

    } 
} 

public class Worker : MarshalByRefObject 
{ 
    public void PrintDomain() 
    { 
     Console.WriteLine("Object is executing in AppDomain \"{0}\"", AppDomain.CurrentDomain.FriendlyName); 
    } 
}