我试图使用反射在AppDomain中执行一些代码。这是我的代码:
AppDomain appDomain = GetSomehowAppDomain();
string typeAssembly = GetTypeAssembly();
string typeName = GetTypeName();
object targetObject = appDomain.CreateInstanceAndUnwrap(typeAssembly, typeName);
MethodInfo methodInfo = targetObject.GetType().GetMethod(methodName);
object result = methodInfo.Invoke(targetObject, methodParams);当此代码在网站下运行时,一切正常。但是,当我从控制台应用程序(调用WCF服务,它试图调用上面的代码)执行此操作时,methodInfo是null,最后一行是NullReferenceException。
顺便说一句,targetObject是System.Runtime.Remoting.Proxies.__TransparentProxy类型的,我假设如果它在GoF模式中代理,就意味着我可以访问类型的成员,这是原始的源程序。但是targetObject没有typeName类型的成员。
使用targetObject.GetType().GetMethods(),我发现它有7个方法:
预计targetObject将成为WorkflowManager类型的代理。
public class WorkflowsManager : MarshalByRefObject, ISerializable, IDisposable, IWorkflowManager
发布于 2012-12-18 22:08:38
感谢Panos Rontogiannis的评论,我意识到我忽略了您的问题中的指示,即您实际上在WCF代码中加载程序集,而不是在控制台应用程序中加载程序集。
确保GAC的实际程序集版本是您希望在WCF代码中使用的版本。
我更新了类似于您的场景的解决方案。
//After building the library, add it to the GAC using "gacutil -i MyLibrary.dll"
using System;
using System.Runtime.Serialization;
namespace MyLibrary
{
[Serializable]
public class MyClass : MarshalByRefObject
{
public string Work(string name)
{
return String.Format("{0} cleans the dishes", name);
}
}
}web应用程序中的服务类定义:
using System;
using System.Reflection;
using System.ServiceModel;
namespace WebApplication1
{
[ServiceContract]
public class MyService : IMyService
{
[OperationContract]
public string DoWork(string name)
{
string methodName = "Work";
object[] methodParams = new object[] { "Alex" };
AppDomain appDomain = AppDomain.CreateDomain("");
appDomain.Load("MyLibrary, Version=1.0.0.3, Culture=neutral, PublicKeyToken=0a6d06b33e075e91");
string typeAssembly = "MyLibrary, Version=1.0.0.3, Culture=neutral, PublicKeyToken=0a6d06b33e075e91";
string typeName = "MyLibrary.MyClass";
object targetObject = appDomain.CreateInstanceAndUnwrap(typeAssembly, typeName);
MethodInfo methodInfo = targetObject.GetType().GetMethod(methodName);
string result = methodInfo.Invoke(targetObject, methodParams).ToString();
return result;
}
}
}调用WCF服务的控制台应用程序:
using System;
using WebApplication1;
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
WebApplication1.MyService myService = new MyService();
Console.WriteLine(myService.DoWork("Alex"));
}
}
}https://stackoverflow.com/questions/13929302
复制相似问题