Enterprises Library中Unity中的Interception
在框架设计中,调用拦截是非常有用的技术,主要用来实现AOP框架。Unity中提供了拦截功能,该功能可以以扩展的方式加入Unity中,也可以单独使用。EL中的帮助文档非常简陋,完全不适合学习,甚至作为查询文档都不合格。网上对其描述的文章也非常少,而且也都是非常简单的描述。所有这些都让我非常失望,我决定自己读Unity的代码来学习一下如何使用Unity中的Interception功能。
在Microsoft.Practices.Unity.Interception.dll中有一个Intercept静态类,这个类提供了一个很好的学习切入点。下面是这个类两个最主要的方法,其他的几个方法在内部都调用了以下两个方法:
public static class Intercept
{
public static object NewInstanceWithAdditionalInterfaces(
Type type,
ITypeInterceptor interceptor,
IEnumerable<IInterceptionBehavior> interceptionBehaviors,
IEnumerable<Type> additionalInterfaces,
params object[] constructorParameters);
public static objectThroughProxyWithAdditionalInterfaces(
Type interceptedType,
object target,
IInstanceInterceptor interceptor,
IEnumerable<IInterceptionBehavior> interceptionBehaviors, IEnumerable<Type> additionalInterfaces);
}
可以看到这两个方法最主要的区别是interceptor参数类型不同,一个是ITypeInterceptor,一个是IInstanceInterceptor。很容易可以猜出,前者为指定类型添加拦截功能,并且在方法内部创建配置好的类型的实例并返回。后者对已经由客户创建好的对象进行配置以实现拦截功能。
下面描述一下NewInstanceWithAdditionalInterfaces方法的用法:
1. type参数用来指示你要拦截的类型,不是所有的类型都可以被拦截,要知道一个类型是否可被拦截,要通过IInterceptor.CanIntercept(T