[英]How to invoke instance method from class library in different appdomain?
I know that there are many similar answers but none of them suit for me. 我知道有很多类似的答案,但它们都不适合我。 I have a class library called MyLibrary. 我有一个名为MyLibrary的类库。 It has only one type. 它只有一种类型。 I'm going to create an instance of my type into another appdomain that why I don't use Activator. 我将创建一个我的类型的实例到另一个appdomain,为什么我不使用Activator。
public class Test
{
public Test()
{
Console.WriteLine("Ctor of Test type.");
}
public void Hello(string name)
{
Console.WriteLine($"Hello {name}! I'm an instance method.");
}
}
I created a simple console application. 我创建了一个简单的控制台应用 This is a code of Main method. 这是Main方法的代码。
static void Main(string[] args)
{
string path = @"example of my path";
AppDomain domain = AppDomain.CreateDomain("mydomain");
Assembly mylibrary = Assembly.LoadFrom(path);
Type typeOfTest = mylibrary.GetType("MyLibrary.Test");
var instanceOfTest = domain.CreateInstanceFrom(path, typeOfTest.FullName);
MethodInfo hello = typeOfTest.GetMethod("Hello");
hello.Invoke(instanceOfTest, new object[] {"Bob"});
}
What is the right way to call Hello method? 调用Hello方法的正确方法是什么? I can create and call static method from Test type but I can do nothing with nonstatic instance method? 我可以从Test类型创建和调用静态方法,但我对非静态实例方法无能为力?
Read this article to get more information: How to load DLL in separate domain and use its methods? 阅读本文以获取更多信息: 如何在单独的域中加载DLL并使用其方法?
You should use the proxy class (Loader in this case). 您应该使用代理类(在本例中为Loader)。 I changed a part of code from article above. 我从上面的文章中更改了部分代码。 Now the Call method takes your custom appdomain. 现在,Call方法将使用您的自定义应用程序域。
public class Loader : MarshalByRefObject
{
object CallInternal(string dll, string typename, string method, object[] parameters)
{
Assembly a = Assembly.LoadFile(dll);
object o = a.CreateInstance(typename);
Type t = o.GetType();
MethodInfo m = t.GetMethod(method);
return m.Invoke(o, parameters);
}
public static object Call(AppDomain domain, string dll, string typename, string method, params object[] parameters)
{
Loader ld = (Loader)domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(Loader).FullName);
object result = ld.CallInternal(dll, typename, method, parameters);
AppDomain.Unload(domain);
return result;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.