Showing posts with label OOP Tips. Show all posts
Showing posts with label OOP Tips. Show all posts

Thursday, 13 August 2009

Creating Proxy Object with Using Generic

public class ObjectA : MarshalByRefObject
{
public void MethodA()
{
Console.WriteLine("MethodA is called.");
}
}

public class ObjectB : MarshalByRefObject
{
public void MethodB()
{
Console.WriteLine("MethoB is called");
}
}
public class GenericProxyManager : RealProxy where TObject : new()
{
private TObject _objectInstance;

public GenericProxyManager(TObject objectInstance) : base(typeof(TObject))
{
this._objectInstance = objectInstance;
}

public static TObject GetProxyObject()
{
TObject objectInstance = new TObject();
GenericProxyManager proxyObject = new GenericProxyManager(objectInstance);
TObject transparentProxyObject = (TObject)proxyObject.GetTransparentProxy();
return transparentProxyObject;
}

public override IMessage Invoke(IMessage msg)
{
IMethodCallMessage message = (IMethodCallMessage)msg;

// Unless you are sure the implementation covers only methods, you need to write some additional code for properties ( get/set )
if (message != null)
{
Console.WriteLine(message.MethodName + " has been handled before it called");
// Write necessary code here - this is before you invoke the method
object methodRetval = message.MethodBase.Invoke(_objectInstance, message.InArgs);
// Write necessary code here - this is after you invoke the method
ReturnMessage retVal = new ReturnMessage(methodRetval, null, 0, message.LogicalCallContext, message);
return retVal;
}
return null;
}
}


Lets execute the following code now
ObjectA obj = GenericProxyManager.GetProxyObject();
obj.MethodA();

ObjectB obj2 = GenericProxyManager.GetProxyObject();
obj2.MethodB();

Result will be

MethodA has been handled before it called
MethodA is called.
MethodB has been handled before it called
MethoB is called