Last active
August 29, 2015 13:55
-
-
Save takeshik/8727283 to your computer and use it in GitHub Desktop.
logging w/ CBO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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