一、什么是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。
代理的实现:
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(); } }