ABP框架详解(六)Aspects
这种AOP式的设计非常类似于Asp.net MVC和WebApi中过滤器(Filter)机制,感觉没有太多可讲述的,只能谈谈设计思路。
框架中AspectAttribute特性用于设置到需要被拦截的Target类型或Target具体方法上,且在设置的时候必须在AspectAttribute的构造器指定一个继承自AbpInterceptorBase<TAspect>类型的子类,该子类会重写BeforeExecution和AfterExecution以设置在Target逻辑真正被执行前和执行后执行拦截逻辑。所重写的两个方法都会以参数的方式获得Target上下文(即IAbpInterceptionContext的子类),另外可以自己定义一个继承自AspectAttribute的特性以便附加自定义数据,在AbpInterceptorBase<TAspect>类中或获得AspectAttribute的实例。具体代码如下:
//THIS NAMESPACE IS WORK-IN-PROGRESS internal abstract class AspectAttribute : Attribute { public Type InterceptorType { get; set; } protected AspectAttribute(Type interceptorType) { InterceptorType = interceptorType; } } internal interface IAbpInterceptionContext { object Target { get; } MethodInfo Method { get; } object[] Arguments { get; } object ReturnValue { get; } bool Handled { get; set; } } internal interface IAbpBeforeExecutionInterceptionContext : IAbpInterceptionContext { } internal interface IAbpAfterExecutionInterceptionContext : IAbpInterceptionContext { Exception Exception { get; } } internal interface IAbpInterceptor<TAspect> { TAspect Aspect { get; set; } void BeforeExecution(IAbpBeforeExecutionInterceptionContext context); void AfterExecution(IAbpAfterExecutionInterceptionContext context); } internal abstract class AbpInterceptorBase<TAspect> : IAbpInterceptor<TAspect> { public TAspect Aspect { get; set; } public virtual void BeforeExecution(IAbpBeforeExecutionInterceptionContext context) { } public virtual void AfterExecution(IAbpAfterExecutionInterceptionContext context) { } }