在.NET 中,可以通过CBO来实现简单的一个msg级别的AOP, 可以参考我以前写的一个简单例子.
采用AOP 的观点来 Log 所有方法的调用
昨天正好培训了一下Remoting, 其实可以用一个realproxy来wrap所有的方法调用,并且可以做一些拦截.为此参考一下简单的代码
事实上,包含了singleton,proxy模式,呵呵
class
Demo:MarshalByRefObject
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
public void SayHello()
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
Console.WriteLine("Hello,China");
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
private Demo()
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
private static Demo _ActInstance = new Demo();
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
public static Demo GetInstance()
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
DemoProxy dp = new DemoProxy(typeof(Demo),_ActInstance);
return (Demo)dp.GetTransparentProxy();
}
}
![None.gif](/Images/OutliningIndicators/None.gif)
![None.gif](/Images/OutliningIndicators/None.gif)
class
DemoProxy : System.Runtime.Remoting.Proxies.RealProxy
![ExpandedBlockStart.gif](/Images/OutliningIndicators/ExpandedBlockStart.gif)
{
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
public DemoProxy(Type tp,Demo target) : base(tp)
{ _target=target;}
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
private Demo _target;
![InBlock.gif](/Images/OutliningIndicators/InBlock.gif)
public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg)
![ExpandedSubBlockStart.gif](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
{
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对象的时候,实际上该实例就是一个透明代理.