.Net AOP切面编程以及EF事务拦截器

AOP切面编程

参考地址

https://www.cnblogs.com/landeanfen/p/4782370.html
https://www.cnblogs.com/stulzq/p/6880394.html

基于Autofac动态代理的AOP切面编程

基于类

    //EFHelper 依赖注入并且通过aop切面
            builder.RegisterType<EFHelper>()//
                .EnableClassInterceptors() //这是基于类,类里面的方法必须是虚方法
           .InterceptedBy(typeof(EFAop));//实现AOP切面

            //在需要切面的地方注入切面
            builder.RegisterType<TestTemp.EFHelper>().InterceptedBy(typeof(AOP.AOPTest)).EnableClassInterceptors();//ef通用查询方法

其他的是需要用到反射的

   //builder.RegisterAssemblyTypes(type.Assembly)//程序集内所有具象类(concrete classes)
            // .Where(cc => cc.Name.EndsWith("Repository") |//筛选
            //             cc.Name.EndsWith("Service")
            //             )
            // .PublicOnly()//只要public访问权限的
            // .Where(cc => cc.IsClass)//只要class型(主要为了排除值和interface类型)
            //                         //.Except<TeacherRepository>()//排除某类型
            //                         //.As(x=>x.GetInterfaces()[0])//反射出其实现的接口,默认以第一个接口类型暴露
            // .AsImplementedInterfaces()//自动以其实现的所有接口类型暴露(包括IDisposable接口)
            //                            .EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
            //                                    .InterceptedBy(typeof(UserAop));//可以直接替换拦截器;

拦截器来实现AOP

参考地址
例如EF事务拦截器

    /// <summary>
    /// EF事务 拦截器
    /// </summary>
    public class EFTransactionFillters : FilterAttribute, IActionFilter
    {
        public TransactionScope scope;
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //执行action前执行这个方法,比如做身份验证
            scope = new TransactionScope();
        }
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //执行action后执行这个方法 比如做操作日志
            //如果不报错,则提交事务
            if (filterContext.Exception == null)
            {
                scope.Complete();
            }
            scope.Dispose();
        }

     
    }

使用

        [EFTransactionFillters]  //使用这个的时候,会锁表(相对于的表)
        public ActionResult Approve(string f)
        {
        }
posted @ 2020-07-21 13:13  Alex_Mercer  阅读(650)  评论(0编辑  收藏  举报