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());
相关文章
相关标签/搜索