Skip to content

Instantly share code, notes, and snippets.

@takeshik
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takeshik/8727283 to your computer and use it in GitHub Desktop.
Save takeshik/8727283 to your computer and use it in GitHub Desktop.
logging w/ CBO
// license:cc0, free to use.
void Main()
{
var x = new Test();
x.Foo();
x.Bar();
}
[Logging]
public class Test
: ContextBoundObject
{
public void Foo()
{
Console.WriteLine("foo!");
}
public void Bar()
{
Console.WriteLine("bar!");
}
}
public class LoggingProxy : RealProxy
{
private readonly MarshalByRefObject _obj;
private readonly Action<IMethodCallMessage> _beforeCall;
private readonly Action<IMethodCallMessage> _afterCall;
public LoggingProxy(Type type, MarshalByRefObject obj, Action<IMethodCallMessage> beforeCall, Action<IMethodCallMessage> afterCall)
: base(type)
{
this._obj = obj;
this._beforeCall = beforeCall;
this._afterCall = afterCall;
}
public override IMessage Invoke(IMessage msg)
{
var ccm = msg as IConstructionCallMessage;
if (ccm != null)
{
RemotingServices.GetRealProxy(this._obj).InitializeServerObject(ccm);
return EnterpriseServicesHelper.CreateConstructionReturnMessage(
ccm, (MarshalByRefObject) this.GetTransparentProxy()
);
}
var mcm = msg as IMethodCallMessage;
if (mcm != null)
{
this._beforeCall(mcm);
var ret = RemotingServices.ExecuteMessage(this._obj, mcm);
this._afterCall(mcm);
return ret;
}
throw new NotSupportedException();
}
}
[AttributeUsage(AttributeTargets.Class)]
public class LoggingAttribute : ProxyAttribute
{
public override MarshalByRefObject CreateInstance(Type serverType)
{
var obj = base.CreateInstance(serverType);
var proxy = new LoggingProxy(
serverType,
obj,
m => Debug.WriteLine("ENTER " + m.MethodName),
m => Debug.WriteLine("LEAVE " + m.MethodName)
);
return (MarshalByRefObject) proxy.GetTransparentProxy();
}
}
ENTER Foo
foo!
LEAVE Foo
ENTER Bar
bar!
LEAVE Bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment