在.NET 中,可以通過CBO來實現簡單的一個msg層級的AOP, 可以參考我以前寫的一個簡單例子. 採用AOP 的觀點來 Log 所有方法的調用
昨天正好培訓了一下Remoting, 其實可以用一個realproxy來wrap所有的方法調用,並且可以做一些攔截.為此參考一下簡單的代碼
事實上,包含了singleton,proxy模式,呵呵
class Demo:MarshalByRefObject
{
public void SayHello()
{
Console.WriteLine("Hello,China");
}
private Demo()
{
}
private static Demo _ActInstance = new Demo();
public static Demo GetInstance()
{
DemoProxy dp = new DemoProxy(typeof(Demo),_ActInstance);
return (Demo)dp.GetTransparentProxy();
}
}
class DemoProxy : System.Runtime.Remoting.Proxies.RealProxy
{
public DemoProxy(Type tp,Demo target) : base(tp) { _target=target;}
private Demo _target;
public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)
{
Console.WriteLine(">>> Inspecting Msg" + (msg as System.Runtime.Remoting.Messaging.IMethodCallMessage).MethodName);
return System.Runtime.Remoting.RemotingServices.ExecuteMessage(_target, (System.Runtime.Remoting.Messaging.IMethodCallMessage)msg);
}
}
其實Demo一定要從MBR繼承,參考了don box 寫的.net essential, 他提到了從MBR繼承,.net clr 保證改類的方法不會被inline,這樣就可以保證代理的正常工作. 如果從CBO繼承,當然CBO是繼承自MBR, proxy可以正常工作, 而且這時候new 一個CBO對象的時候,實際上該執行個體就是一個透明代理.