Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the difference between AppDomain.CreateInstance and Activator.CreateInstance?

I want to ask a question to realize the difference between AppDomain and Activator, I loaded my dll via appdomain.CreateInstance. But I realized that more method to create instance. Therefore when or where do I choose this method? Example1:

    // 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);

Example2:

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;
}

Example3:

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);
    }
}

Can you explain why do I need more methods or what are the differences?

like image 741
loki Avatar asked Mar 13 '12 09:03

loki


2 Answers

From sscli2.0 source code, it looks like the "CreateInstance" method calls in AppDomain class always delegates the call to Activator.

The sole purpose of the (almost static) Activator class is to "Create" instances of various classes, while AppDomain is introduced for quite different (and perhaps more ambitious) purposes, e.g.:

  1. A light-weight unit of application isolation;
  2. Optimize memory consumption because AppDomains can be Unloaded.
  3. ...

The 1st and the 3rd example are straightforward, just as zmbq noted. I guess your 2nd example is from this post, where the author showed how to unload an out-of-date proxy using AppDomain.

like image 170
Jiaji Wu Avatar answered Sep 29 '22 05:09

Jiaji Wu


The first one creates an instance of type Example from the assembly 'example', and calls MethodA on it.

The third one creates an instance of MyType in a different AppDomain

I'm not sure about the second, I don't know what this is, but it seems to create a class in the current app-domain - that is, it's similar to the first.

like image 36
zmbq Avatar answered Sep 29 '22 04:09

zmbq