k10n
Jim Klopfenstein's Radio Weblog

 



Subscribe to "k10n" in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.
 
 

MyGenericProxy

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:
csc /t:exe MyGenericProxy.cs
and run it like this:
MyGenericProxy Apple Grape


Click here to visit the Radio UserLand website. © Copyright 2003 Jim Klopfenstein.
Last update: 2/10/2003; 8:43:53 AM.