Standalone Unity Interception

Unity的拦截技术可以独立使用,你不需要使用Microsoft.Practices.Unity.dll、Microsoft.Practices.Unity.Configuration.dll、Microsoft.Practices.ServiceLocation.dll。而只需要使用Microsoft.Practices.Unity.Interception.dll、Microsoft.Practices.Unity.Interception.Configuration.dll。它提供了Intercept静态类型用来创建代理类型。比如上一篇演示的InterfaceInterceptor也可以如下编写代码:

1 IServiceProvider myObject = Intercept.ThroughProxy<IServiceProvider>(
2   new MyObject2(),
3   new InterfaceInterceptor(),
4   new[] { new MyInterceptionBehavior() }
5 );
6 
7 myObject.GetService(null);

上一篇演示的VirtualMethodInterceptor也可以编写如下代码:

1 MyObject3 myObject = Intercept.NewInstance<MyObject3>(new VirtualMethodInterceptor(), new[] { new MyInterceptionBehavior() });
2 
3 myObject.DoWork();

ThroughProxy和NewInstance函数应用于不同的场景。对于InterfaceInterceptor、TransparentProxyInterceptor这样的IInstanceInterceptor通过调用ThroughProxy,而VirtualMethodInterceptor这样的ITypeInterceptor需要通过调用NewInstance函数创建。

原文地址:https://www.cnblogs.com/junchu25/p/2631586.html