Suzanne Soy
Suzanne Soy

Reputation: 3244

How do I call a method in another AppDomain

How do I call a method on an object I created in another AppDomain? I would like to avoid using CreateInstanceFromAndUnwrap because that would require that I reference the DLL I want to operate on.

public static void Main() {
    // Create domain
    AppDomain domain = AppDomain.CreateDomain("Foo");

    // Load assembly
    domain.Load("C:\\Foo.dll");

    // Create instance of class
    System.Runtime.Remoting.ObjectHandle inst
        = domain.CreateInstance("C:\\Foo.dll", "MyNamespace.MyClass");

    // Call method -- How can I do this ???
    object result = inst.PleaseCallMethod("MyMethod", "param1", 42, "p3", null);
}

And in Foo.dll I would have:

namespace MyNamespace {
    public class MyClass {
        public string MyMethod(string p1, int p2, string p3, string p4) {
            return "...";
        }
    }
}

Also, how would I call a static method, without first creating an instance of the (possibly static) class that contains it?

Upvotes: 3

Views: 5322

Answers (1)

Linky
Linky

Reputation: 604

You can call:

domain.DoCallBack(() => Console.WriteLine("DoCallBack: {0}", AppDomain.CurrentDomain.FriendlyName));

but that requires that the assembly running the code to be loaded into the new appdomain.

If your new appdomain has a different base path and/or requires an assembly that can't be resolved by the runtime in the new appdomain you may need to create an isolated entry assembly that you invoke in DoCallBack and from this one load the assemblies from their desired location.

Upvotes: 5

Related Questions