Unity的三种Interceptor

Unity默认提供了三种拦截器:TransparentProxyInterceptor、InterfaceInterceptor、VirtualMethodInterceptor。

TransparentProxyInterceptor:代理实现基于.NET Remoting技术,它可拦截对象的所有函数。缺点是被拦截类型必须派生于MarshalByRefObject。示例如下:

 1 public class MyObject : MarshalByRefObject
 2 {
 3   public String Name { get; set; }
 4 }
 5 
 6 IUnityContainer unityContainer = new UnityContainer();
 7 
 8 unityContainer.AddNewExtension<Interception>();
 9 unityContainer.RegisterType<MyObject>(new Interceptor<TransparentProxyInterceptor>(), new InterceptionBehavior(new NotifyPropertyChangedBehavior()));
10 
11 MyObject myObject = unityContainer.Resolve<MyObject>();
12 
13 ((INotifyPropertyChanged)myObject).PropertyChanged += new PropertyChangedEventHandler((sender, e) => Console.WriteLine(e.PropertyName));
14 
15 myObject.Name = “hello, world”;

InterfaceInterceptor:只能对一个接口做拦截,好处时只要目标类型实现了指定接口就可以拦截。示例如下:

 1 public class MyObject2 : IServiceProvider
 2 {
 3 
 4   #region IServiceProvider Members
 5 
 6   public object GetService(Type serviceType)
 7   {
 8     return null;
 9   }
10 
11   #endregion
12 }
13 
14 public sealed class MyInterceptionBehavior : IInterceptionBehavior
15 {
16   #region IInterceptionBehavior Members
17 
18   public Boolean WillExecute
19   {
20     get { return true; }
21   }
22 
23   public IEnumerable<Type> GetRequiredInterfaces()
24   {
25     return new Type[0];
26   }
27 
28   public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
29   {
30     return getNext()(input, getNext);
31   }
32 
33   #endregion
34 }
35 
36 IUnityContainer unityContainer = new UnityContainer();
37 
38 unityContainer.AddNewExtension<Interception>();
39 unityContainer.RegisterType<IServiceProvider, MyObject2>(“MyObject2″,
40   new Interceptor<InterfaceInterceptor>(),
41   new InterceptionBehavior<MyInterceptionBehavior>()
42 );
43 
44 IServiceProvider myObject = unityContainer.Resolve<IServiceProvider>(“MyObject2″);
45 
46 myObject.GetService(typeof(MyObject2));

注册类型时需要显示指定被拦截接口类型。

VirtualMethodInterceptor:对virtual函数进行拦截。缺点是如果被拦截类型没有virtual函数则无法拦截,这个时候如果类型实现了某个特定接口可以改用InterfaceInterceptor。看一个简单示例:

 1 public class MyObject3
 2 {
 3   public virtual void DoWork()
 4   {
 5 
 6   }
 7 }
 8 
 9 IUnityContainer unityContainer = new UnityContainer();
10 
11 unityContainer.AddNewExtension<Interception>();
12 unityContainer.RegisterType<MyObject3>(
13   new Interceptor<VirtualMethodInterceptor>(),
14   new InterceptionBehavior<MyInterceptionBehavior>()
15 );
16 
17 MyObject3 myObject = unityContainer.Resolve<MyObject3>();
18 
19 myObject.DoWork();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值