简体   繁体   English

如何在另一个AppDomain中调用方法

[英]How do I call a method in another AppDomain

How do I call a method on an object I created in another AppDomain? 如何在另一个AppDomain中创建的对象上调用方法? I would like to avoid using CreateInstanceFromAndUnwrap because that would require that I reference the DLL I want to operate on. 我想避免使用CreateInstanceFromAndUnwrap因为这将要求我引用要操作的DLL。

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: Foo.dll我将拥有:

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? 另外,如何在不首先创建包含静态方法的类的实例的情况下调用静态方法?

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. 但这要求将运行代码的程序集加载到新的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. 如果您的新应用程序域具有不同的基本路径和/或需要新的应用程序域中的运行时无法解析的程序集,则可能需要创建一个在DoCallBack中调用的隔离条目程序集,然后从中加载该程序集他们想要的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM