AOP面相切面编程,通常适用于对垂直业务的横截面的业务进行统一处理,如针对于服务统一日志记录、异常抓取、缓存拦截等等。
本文针对于AutoFac的AOP切面编程,AutoFac的AOP 底层使用的是Castle.Core,所以类库需要引用Castle.Core、Autofac.Extras.DynamicProxy。
项目简述(从上到下):
1、调用层(WEB、Service、Job)
2、业务处理层(Core)
3、数据处理层(BLL)
4、数据库处理层(DAL)
1、先进行业务处理层注入
public static class AutofacContainerBuilderCore
{
public static IContainer container;
public static void BuildContainer()
{
var builder = new ContainerBuilder();
builder.RegisterType<业务实现类>().As<业务类接口>().EnableInterfaceInterceptors() //开启切面服务
.InterceptedBy(typeof(ExceptionInterceptor)) //异常记录
.InterceptedBy(typeof(WatchInterceptor)); //性能监控
container = builder.Build();
}
}
2、增加Attr属性标签
/// <summary> /// 不需要打标记性能监测标签(切入点) /// </summary> [AttributeUsage(AttributeTargets.Method, Inherited = true)] public class NoNeedWatchInterceptorAttribute : Attribute { }
3、切面Hander处理类
/// <summary> /// 性能监测 /// </summary> public class WatchInterceptor : IInterceptor { public void Intercept(IInvocation invocation) { var attributes = invocation.MethodInvocationTarget.GetCustomAttributes(typeof(NoNeedWatchInterceptorAttribute), false); if (!attributes.Any()) { string batch = Guid.NewGuid().ToString(); Stopwatch watch = new Stopwatch(); watch.Start(); try { invocation.Proceed(); watch.Stop(); //日志记录 } catch (Exception ex) { watch.Stop(); throw ex; } } else { invocation.Proceed(); //执行注册的Method方法 } } }
4、具体类方法打标记
/// <summary> /// 数据查询By——Id集合 /// </summary> /// <param name="request">ID集合对象</param> /// <returns></returns> [NoNeedWatchInterceptor] [NoNeedExceptionInterceptor] [CacheInterceptor(CacheType.Local, CacheSetting.CacheTime, true,typeof(GoodsDto))] public List<数据对象> 查询数据方法(Request request) { var temp对象= bll.查询数据库(request); var 数据对象 = (业务数据组装+AutoFac转换)temp对象; return 数据对象; }