一、什么是AOP
AOP(aspect oriented programming)面向切面編程,意思是面向某一個方向編程,和裝飾器和代理作用有點像,但是解耦成都比前邊的要好。
我們通過AOP實現日志添加、異常處理、事務處理,消息加工等。
C# 通過 System.Runtime.Remoting.Proxies;請諒解框架來實現,其內部是利用了反射的原理。
二、RealProxy的使用
我們有一組功能:
public interface BaseBox { void Open(); void Close(); } public class SmallBox:BaseBox { public void Open() { Console.WriteLine("small box open."); } public void Close() { Console.WriteLine("small box close."); } } public class BigBox : BaseBox { public void Open() { Console.WriteLine("big box open."); } public void Close() { Console.WriteLine("big box close."); } }
因為框架限制,抽象類必須是interface類型的,不能是abstract class。但是可以繼承MarsalByRef的類
代理的實現:
public class MyProxy<T> : RealProxy where T: BaseBox { private readonly T _target; public MyProxy(T target) :base(typeof(T)) { _target = target; } //裝飾部分 private void PrintTime() { Console.WriteLine(DateTime.Now.ToString()); } public override IMessage Invoke(IMessage msg) { IMethodCallMessage methodCallMessage = msg as IMethodCallMessage; MethodInfo methodInfo = methodCallMessage.MethodBase as MethodInfo; try { PrintTime(); var result = methodInfo.Invoke(_target, methodCallMessage.InArgs); return new ReturnMessage(result, null, 0, methodCallMessage.LogicalCallContext, methodCallMessage); } catch (Exception ex) { return new ReturnMessage(ex, methodCallMessage); } } }
代理的使用:
class Program { static void Main(string[] args) { BaseBox box = new BigBox() as BaseBox; MyProxy<BaseBox> boxProxy = new MyProxy<BaseBox>(box); var mbox = boxProxy.GetTransparentProxy() as BaseBox; mbox.Open(); mbox.Close(); Console.ReadLine(); } }
