2012-03-13 16 views
5

我想問一個問題,以實現應用程序域和激活之間的區別,我通過appdomain.CreateInstance加載我的DLL。但是我意識到創建實例的更多方法。因此,我何時或在哪裏選擇這種方法? 例1:是什麼AppDomain.CreateInstance和Activator.CreateInstance之間的區別?

// Use the file name to load the assembly into the current 
    // application domain. 
    Assembly a = Assembly.Load("example"); 
    // Get the type to use. 
    Type myType = a.GetType("Example"); 
    // Get the method to call. 
    MethodInfo myMethod = myType.GetMethod("MethodA"); 
    // Create an instance. 
    object obj = Activator.CreateInstance(myType); 
    // Execute the method. 
    myMethod.Invoke(obj, null); 

例2:

public WsdlClassParser CreateWsdlClassParser() 
{ 
    this.CreateAppDomain(null); 

    string AssemblyPath = Assembly.GetExecutingAssembly().Location; 
    WsdlClassParser parser = null; 
    try 
    {     
     parser = (WsdlClassParser) this.LocalAppDomain.CreateInstanceFrom(AssemblyPath, 
              typeof(Westwind.WebServices.WsdlClassParser).FullName).Unwrap() ;     
    } 
    catch (Exception ex) 
    { 
     this.ErrorMessage = ex.Message; 
    }       
    return parser; 
} 

示例3:

private static void InstantiateMyTypeSucceed(AppDomain domain) 
{ 
    try 
    { 
     string asmname = Assembly.GetCallingAssembly().FullName; 
     domain.CreateInstance(asmname, "MyType"); 
    } 
    catch (Exception e) 
    { 
     Console.WriteLine(); 
     Console.WriteLine(e.Message); 
    } 
} 

你能解釋一下爲什麼我需要更多的方法或有什麼區別?

回答

2

從sscli2.0源代碼,它看起來像在AppDomain類中的「CreateInstance」方法調用始終將呼叫委託給Activator

的(幾乎是靜態)的唯一目的激活類是「創造」各種類的實例,而的AppDomain介紹了一種完全不同的(或許更宏大的)目的,例如:

  1. 的輕重量單元的應用程序隔離;
  2. 優化內存消耗,因爲應用程序域可以被卸載。
  3. ...

第1和第3個例子很簡單,就像zmbq指出。我猜你的第二個例子是從這個post,在這裏筆者展示瞭如何使用AppDomain中卸載一個徹頭徹尾的最新的代理。

2

第一個創建從組件「示例」 Example類型的一個實例,並在其上調用MethodA

第三個不同AppDomain

創建的MyType一個實例,我不知道第二個,我不知道是什麼this是,但它似乎當前創建一個類應用程序域 - 也就是說,它與第一個類似。

相關問題