C# unity 的 IInterceptionBehavior實現aop攔截器

之前項目寫過使用unity的 IInterceptionBehavior 實現aop攔截器,時間很少就忘了,項目找不到了,而後呢,寫個簡單的例子,用的收直接用就好了,簡單實用,至於什麼用,mvc的attribut屬性用法差很少,寫過濾器還能夠的mvc

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using Unity;
 7 using Unity.Interception;
 8 using Unity.Interception.ContainerIntegration;
 9 using Unity.Interception.InterceptionBehaviors;
10 using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception;
11 using Unity.Interception.PolicyInjection.Pipeline;
12 
13 namespace AOP
14 {
15     public interface IServiceProvider2
16     {
17         string GetServicetest();
18         string GetServicetest2();
19     }
20     public class MyObject2 : IServiceProvider2
21     {
22 
23         public string GetServicetest()
24         {
25             return "sttt";
26         }
27         public string GetServicetest2()
28         {
29             throw new Exception("9999999999999999999");
30         }
31     }
32 
33     public sealed class MyInterceptionBehavior : IInterceptionBehavior
34     {
35         #region IInterceptionBehavior Members
36 
37         public Boolean WillExecute
38         {
39             get { return true; }
40         }
41 
42         public IEnumerable<Type> GetRequiredInterfaces()
43         {
44             return new Type[0];
45         }
46 
47         public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
48         {
49             return getNext()(input, getNext);
50         }
51 
52         #endregion
53 
54     
55     }
56 
57 
58    public class Test
59     {
60         public void test()
61         {
62             IUnityContainer unityContainer = new UnityContainer();
63 
64             unityContainer.AddNewExtension<Interception>();
65             unityContainer.RegisterType<IServiceProvider2, MyObject2>("MyObject2",
66             new Interceptor<InterfaceInterceptor>(),
67             new InterceptionBehavior<MyInterceptionBehavior>()
68             );
69 
70             IServiceProvider2 myObject = unityContainer.Resolve<IServiceProvider2>("MyObject2");
71             myObject.GetServicetest();
72             myObject.GetServicetest2();
73 
74         }
75     }
76 
77 
78 
79    
80 }

 

main 方法裏調用一下就能夠了ide

Test t = new Test();
t.test();ui

至於原理,那確定用到動態代理了,至於動態代理,怎麼實現的,我不太會spa

 動態代理這個樣子: var generator = new ProxyGenerator(); var animal = generator.CreateClassProxy<Animal>(new AnimalInterceptor());
相關文章
相關標籤/搜索