【转】.NET 自带的动态代理+Expression 实现AOP
生活随笔
收集整理的這篇文章主要介紹了
【转】.NET 自带的动态代理+Expression 实现AOP
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
下面代碼(摘抄之別處,原創在哪不知)是采用TransparentProxy和RealProxy實現對象的動態代理。礙于其使用反射調用方法,所以就小試著將反射改成Expression以提高執行的效率。第15行就是原來代碼中反射調用方法的關鍵代碼。
?
1 using System.Runtime.Remoting.Proxies;2 using System.Runtime.Remoting.Messaging;3 //RealProxy4 public class MyRealProxy<T>:RealProxy5 {6 private T _target;7 public MyRealProxy(T target) : base(typeof(T))8 {9 this._target = target; 10 } 11 public override IMessage Invoke(IMessage msg) 12 { 13 PreProceede(msg); 14 IMethodCallMessage callMessage = (IMethodCallMessage)msg; 15 object returnValue = callMessage.MethodBase.Invoke(this._target, callMessage.Args); 16 PostProceede(msg); 17 return new ReturnMessage(returnValue, new object[0], 0, null, callMessage); 18 } 19 public void PreProceede(IMessage msg) 20 { 21 Console.WriteLine("方法執行前"); 22 } 23 public void PostProceede(IMessage msg) 24 { 25 Console.WriteLine("方法執行后"); 26 } 27 } 28 //TransparentProxy 29 public static class TransparentProxy 30 { 31 public static T Create<T>() 32 { 33 T instance = Activator.CreateInstance<T>(); 34 MyRealProxy<T> realProxy = new MyRealProxy<T>(instance); 35 T transparentProxy = (T)realProxy.GetTransparentProxy(); 36 return transparentProxy; 37 } 38 }其他的輔助類
1 public class User 2 {3 public string Name { get; set; }4 public string PassWord { get; set; }5 }6 7 public interface IUserProcessor8 {9 void RegUser(User user); 10 } 11 12 public class UserProcessor : MarshalByRefObject, IUserProcessor 13 { 14 public void RegUser(User user) 15 { 16 Console.WriteLine("Already registered."); 17 } 18 19 public string RegUser2(User user) 20 { 21 Console.WriteLine("Already registered."); 22 return "OK"; 23 } 24 } 25 26 public class RemotingProxy 27 { 28 public void Execute() 29 { 30 try 31 { 32 User user = new User() { Name = "HK", PassWord = "12345" }; 33 UserProcessor userprocessor = TransparentProxy.Create<UserProcessor>(); 34 userprocessor.RegUser(user); 35 Console.WriteLine(userprocessor.RegUser2(user)); 36 } 37 catch (Exception ex) 38 { 39 throw ex; 40 } 41 42 } 43 }將15行替換為如下Expression實現的代碼。
分類:?C#
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的【转】.NET 自带的动态代理+Expression 实现AOP的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】D365 FO第三方访问https
- 下一篇: 2017春节信用卡还款日期怎么算