1. 程式人生 > 實用技巧 >.Net AOP切面程式設計以及EF事務攔截器

.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)
        {
        }