what is the difference between AppDomain.CreateInstance and Activator.CreateInstance?
Asked Answered
V

2

6

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?

Valuator answered 13/3, 2012 at 9:2 Comment(0)
M
4

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.

Marie answered 13/3, 2012 at 13:14 Comment(0)
L
2

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.

Lydialydian answered 13/3, 2012 at 9:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.