castle之动态代理
動態代理 DynamicProxy,這里說的動態代理是直接使用Castle.net 中提供的,并非自己實現的,因為別人寫的很好,拿著用就行了。
動態代理的工作模式:
一般我們獲取一個類型的實例都是通過 new 關鍵字,例如 var c = new Class1(); 通過動態代理的話,我們獲取一個實例是通過代理方法獲取的,generator.CreateClassProxy(type, interceptor); 其中Type是要代理的類型,也就是Class1(); interceptor則是實際執行代理的攔截器。
為什么要用動態代理:
簡單的說,例如我Class1與Class2都有自己的方法,我現在想給這兩給類的每個方法都添加一個日志操作,如果不通過代理我們怎么做呢?每個函數開始增加一句Log.Enter();結束的時候增加一個Log.Exit(); 通過動態代理,我們可以增加一個攔截器,攔截器中,可以先執行Log.Enter();然后執行實際操作,最后在執行Log.Exit(); ?這樣我們就不需要去修改 Class1與Class2兩個類。說白了就是為了符合OCP.
實現
1 public interface ISaySomething 2 { 3 void sayHK(); 4 } 5 6 public class Say : ISaySomething 7 { 8 public virtual void sayHK() 9 { 10 Console.WriteLine("hk"); 11 } 12 }這個方法一定要用虛方法,因為會被代理類重寫。
1 public class SayInterceptorProxy : IInterceptor 2 { 3 string _user; 4 public SayInterceptorProxy(string user) 5 { 6 this._user = user; 7 } 8 9 public void Intercept(IInvocation invocation) 10 { 11 if (_user == "hk") 12 { 13 beforeDoSomething(); 14 invocation.Proceed(); 15 afterDoSomething() 16 } 17 else 18 { 19 Console.WriteLine("{0}沒有權限執行", _user); 20 } 21 } 22 }這個是代理類,必須要繼承?IInterceptor 接口 在執行你的邏輯方法之前或者之后,你都可以加上你自己的邏輯。其中 invocation 里面放的是代理方法的所有詳細信息。
1 public void test() 2 { 3 ProxyGenerator proxyGenerator = new ProxyGenerator(); 4 var handle = new SayInterceptorProxy[] { new SayInterceptorProxy("wy") }; 5 ISaySomething iSay = proxyGenerator.CreateClassProxy<Say>(handle); 6 iSay.sayHK(); 7 }這是調用執行過程。
?
轉載于:https://www.cnblogs.com/HKKD/p/7283810.html
總結
以上是生活随笔為你收集整理的castle之动态代理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: poj-1062-昂贵的聘礼
- 下一篇: 保险退保怎么退