using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Proxies;
namespace InjectProxy
{
public interface IColor
{
string whatColor();
}
public class Grape : MarshalByRefObject, IColor
{
public string whatColor() { return "purple"; }
}
public class Apple : MarshalByRefObject, IColor
{
public string whatColor() { return "red"; }
}
class MyGenericProxy : RealProxy
{
Type type;
public MyGenericProxy(Type type) : base(type) { this.type = type; }
public void ChangeType(Type newType) { this.type = newType; }
public override IMessage Invoke(IMessage request)
{
IMethodCallMessage call = (IMethodCallMessage)request;
Object o = Construct(type);
Object res = type.InvokeMember(
call.MethodName,BindingFlags.InvokeMethod,null,o,call.InArgs);
return new ReturnMessage(res, null, 0, null, call);
}
Object Construct(Type type)
{
Type [] ta = new Type[0];
ConstructorInfo ci = type.GetConstructor(ta);
return ci.Invoke(ta);
}
}
class Tester
{
static void Main(string[] args)
{
MyGenericProxy gp;
gp = new MyGenericProxy(Type.GetType("InjectProxy."+args[0]));
Object obj = gp.GetTransparentProxy();
Console.WriteLine(((IColor)obj).whatColor());
gp.ChangeType(Type.GetType("InjectProxy."+args[1]));
Console.WriteLine(((IColor)obj).whatColor());
}
}
}
Build it with this command line: