欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

利用AOP實現SqlSugar自動事務

 更新時間:2017年10月26日 14:48:03   作者:若若若邪  
這篇文章主要為大家詳細介紹了利用AOP實現SqlSugar自動事務,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了如何利用AOP實現SqlSugar自動事務,供大家參考,具體內容如下

先看一下效果,帶接口層的三層架構:

BL層:

 public class StudentBL : IStudentService
   {
     private ILogger mLogger;
     private readonly IStudentDA mStudentDa;
     private readonly IValueService mValueService;

     public StudentService(IStudentDA studentDa,IValueService valueService)
     {
       mLogger = LogManager.GetCurrentClassLogger();
       mStudentDa = studentDa;
       mValueService = valueService;

     }

     [TransactionCallHandler]
     public IList<Student> GetStudentList(Hashtable paramsHash)
     {
       var list = mStudentDa.GetStudents(paramsHash);
       var value = mValueService.FindAll();
       return list;
     }
   }

假設GetStudentList方法里的mStudentDa.GetStudents和mValueService.FindAll不是查詢操作,而是更新操作,當一個失敗另一個需要回滾,就需要在同一個事務里,當一個出現異常就要回滾事務。

特性TransactionCallHandler就表明當前方法需要開啟事務,并且當出現異常的時候回滾事務,方法執(zhí)行完后提交事務。

DA層:

 public class StudentDA : IStudentDA
   {

     private SqlSugarClient db;
     public StudentDA()
     {
       db = SugarManager.GetInstance().SqlSugarClient;
     }
     public IList<Student> GetStudents(Hashtable paramsHash)
     {
       return db.Queryable<Student>().AS("T_Student").With(SqlWith.NoLock).ToList();
     }
   }

對SqlSugar做一下包裝

 public class SugarManager
   {
     private static ConcurrentDictionary<string,SqlClient> _cache =
       new ConcurrentDictionary<string, SqlClient>();
     private static ThreadLocal<string> _threadLocal;
     private static readonly string _connStr = @"Data Source=localhost;port=3306;Initial Catalog=thy;user id=root;password=xxxxxx;Charset=utf8";
     static SugarManager()
     {
       _threadLocal = new ThreadLocal<string>();
     }

     private static SqlSugarClient CreatInstance()
     {
       SqlSugarClient client = new SqlSugarClient(new ConnectionConfig()
       {
         ConnectionString = _connStr, //必填
         DbType = DbType.MySql, //必填
         IsAutoCloseConnection = true, //默認false
         InitKeyType = InitKeyType.SystemTable
       });
       var key=Guid.NewGuid().ToString().Replace("-", "");
       if (!_cache.ContainsKey(key))
       {
         _cache.TryAdd(key,new SqlClient(client));
         _threadLocal.Value = key;
         return client;
       }
       throw new Exception("創(chuàng)建SqlSugarClient失敗");
     }
     public static SqlClient GetInstance()
     {
       var id= _threadLocal.Value;
       if (string.IsNullOrEmpty(id)||!_cache.ContainsKey(id))
         return new SqlClient(CreatInstance());
       return _cache[id];
     }


     public static void Release()
     {
       try
       {
         var id = GetId();
         if (!_cache.ContainsKey(id))
           return;
         Remove(id);
       }
       catch (Exception e)
       {
         throw e;
       }
     }
     private static bool Remove(string id)
     {
       if (!_cache.ContainsKey(id)) return false;

       SqlClient client;

       int index = 0;
       bool result = false;
       while (!(result = _cache.TryRemove(id, out client)))
       {
         index++;
         Thread.Sleep(20);
         if (index > 3) break;
       }
       return result;
     }
     private static string GetId()
     {
       var id = _threadLocal.Value;
       if (string.IsNullOrEmpty(id))
       {
         throw new Exception("內部錯誤: SqlSugarClient已丟失.");
       }
       return id;
     }

     public static void BeginTran()
     {
       var instance=GetInstance();
       //開啟事務
       if (!instance.IsBeginTran)
       {
         instance.SqlSugarClient.Ado.BeginTran();
         instance.IsBeginTran = true;
       }
     }

     public static void CommitTran()
     {
       var id = GetId();
       if (!_cache.ContainsKey(id))
         throw new Exception("內部錯誤: SqlSugarClient已丟失.");
       if (_cache[id].TranCount == 0)
       {
         _cache[id].SqlSugarClient.Ado.CommitTran();
         _cache[id].IsBeginTran = false;
       }
     }

     public static void RollbackTran()
     {
       var id = GetId();
       if (!_cache.ContainsKey(id))
         throw new Exception("內部錯誤: SqlSugarClient已丟失.");
       _cache[id].SqlSugarClient.Ado.RollbackTran();
       _cache[id].IsBeginTran = false;
       _cache[id].TranCount = 0;
     }

     public static void TranCountAddOne()
     {
       var id = GetId();
       if (!_cache.ContainsKey(id))
         throw new Exception("內部錯誤: SqlSugarClient已丟失.");
       _cache[id].TranCount++;
     }
     public static void TranCountMunisOne()
     {
       var id = GetId();
       if (!_cache.ContainsKey(id))
         throw new Exception("內部錯誤: SqlSugarClient已丟失.");
       _cache[id].TranCount--;
     }
   }

_cache保存SqlSugar實例,_threadLocal確保同一線程下取出的是同一個SqlSugar實例。

不知道SqlSugar判斷當前實例是否已經開啟事務,所以又將SqlSugar包了一層。

 public class SqlClient
   {
     public SqlSugarClient SqlSugarClient;
     public bool IsBeginTran = false;
     public int TranCount = 0;

     public SqlClient(SqlSugarClient sqlSugarClient)
     {
       this.SqlSugarClient = sqlSugarClient;
     }
   }

IsBeginTran標識當前SqlSugar實例是否已經開啟事務,TranCount是一個避免事務嵌套的計數器。

一開始的例子

 [TransactionCallHandler]
      public IList<Student> GetStudentList(Hashtable paramsHash)
      {
        var list = mStudentDa.GetStudents(paramsHash);
        var value = mValueService.FindAll();
        return list;
      }

TransactionCallHandler表明該方法要開啟事務,但是如果mValueService.FindAll也標識了TransactionCallHandler,又要開啟一次事務?所以用TranCount做一個計數。

使用Castle.DynamicProxy

要實現標識了TransactionCallHandler的方法實現自動事務,使用Castle.DynamicProxy實現BL類的代理

Castle.DynamicProxy一般操作

 public class MyClass : IMyClass
  {
    public void MyMethod()
    {
      Console.WriteLine("My Mehod");
    }
 }
 public class TestIntercept : IInterceptor
   {
     public void Intercept(IInvocation invocation)
     {
       Console.WriteLine("before");
       invocation.Proceed();
       Console.WriteLine("after");
     }
   }

  var proxyGenerate = new ProxyGenerator();
  TestIntercept t=new TestIntercept();
  var pg = proxyGenerate.CreateClassProxy<MyClass>(t);
  pg.MyMethod();
  //輸出是
  //before
  //My Mehod
  //after

before就是要開啟事務的地方,after就是提交事務的地方

最后實現

 public class TransactionInterceptor : IInterceptor
   {
     private readonly ILogger logger;
     public TransactionInterceptor()
     {
       logger = LogManager.GetCurrentClassLogger();
     }
     public void Intercept(IInvocation invocation)
     {
       MethodInfo methodInfo = invocation.MethodInvocationTarget;
       if (methodInfo == null)
       {
         methodInfo = invocation.Method;
       }

       TransactionCallHandlerAttribute transaction =
         methodInfo.GetCustomAttributes<TransactionCallHandlerAttribute>(true).FirstOrDefault();
       if (transaction != null)
       {
         SugarManager.BeginTran();
         try
         {
           SugarManager.TranCountAddOne();
           invocation.Proceed();
           SugarManager.TranCountMunisOne();
           SugarManager.CommitTran();
         }
         catch (Exception e)
         {
           SugarManager.RollbackTran();
           logger.Error(e);
           throw e;
         }

       }
       else
       {
         invocation.Proceed();
       }
     }
   }
   [AttributeUsage(AttributeTargets.Method, Inherited = true)]
   public class TransactionCallHandlerAttribute : Attribute
   {
     public TransactionCallHandlerAttribute()
     {

     }
   }

Autofac與Castle.DynamicProxy結合使用

創(chuàng)建代理的時候一個BL類就要一次操作

 proxyGenerate.CreateClassProxy<MyClass>(t);

而且項目里BL類的實例化是交給IOC容器控制的,我用的是Autofac。當然Autofac和Castle.DynamicProxy是可以結合使用的

using System.Reflection;
using Autofac;
using Autofac.Extras.DynamicProxy;
using Module = Autofac.Module;
public class BusinessModule : Module
  {
    protected override void Load(ContainerBuilder builder)
    {
      var business = Assembly.Load("FTY.Business");
      builder.RegisterAssemblyTypes(business)
        .AsImplementedInterfaces().InterceptedBy(typeof(TransactionInterceptor)).EnableInterfaceInterceptors();
      builder.RegisterType<TransactionInterceptor>();
    }
  }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • C#的WEBBROWSER與JS交互小結

    C#的WEBBROWSER與JS交互小結

    這篇文章主要介紹了C#的WEBBROWSER與JS交互方法,詳細講述了與頁面標簽的交互以及數據交互的方法,需要的朋友可以參考下
    2014-11-11
  • 那些年,我還在學習C# 學習筆記續(xù)

    那些年,我還在學習C# 學習筆記續(xù)

    那些年學習C#,就是對C#相關的一些知識有一個了解,等到要用時才不會找不到方向,比如說擴展方法,開始時怎么覺得沒有用,后來了解到asp.net MVC,它可以用來擴展Html類,比如做一個分頁的方法;所以對一門語言了解寬一些是沒有壞處的
    2012-03-03
  • C#中的正則表達式雙引號問題

    C#中的正則表達式雙引號問題

    正則表達式獲取CSS里面的圖片的例子,里面有URL里面的圖片地址有雙引號,要注意用兩個雙引號表示
    2015-05-05
  • c#并行任務多種優(yōu)化方案分享(異步委托)

    c#并行任務多種優(yōu)化方案分享(異步委托)

    c#并行任務多種優(yōu)化方案分享,使用異步委托+回調函數方式實現,大家參考使用吧
    2013-12-12
  • timespan使用方法詳解

    timespan使用方法詳解

    TimeSpan是用來表示一個時間段的實例,兩個時間的差可以構成一個TimeSpan實例,現在就來介紹一下使用方法
    2014-04-04
  • 深入解析C#中的交錯數組與隱式類型的數組

    深入解析C#中的交錯數組與隱式類型的數組

    這篇文章主要介紹了深入解析C#中的交錯數組與隱式類型的數組,隱式類型的數組通常與匿名類型以及對象初始值設定項和集合初始值設定項一起使用,需要的朋友可以參考下
    2016-01-01
  • C#遞歸實現將一整數逆序后放入一數組中

    C#遞歸實現將一整數逆序后放入一數組中

    這篇文章主要介紹了C#遞歸實現將一整數逆序后放入一數組中,是遞歸算法的一個簡單應用,需要的朋友可以參考下
    2014-10-10
  • C#中TCP粘包問題的解決方法

    C#中TCP粘包問題的解決方法

    這篇文章主要為大家詳細介紹了C#中TCP粘包問題的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-07-07
  • C#打包部署并把.net framework框架打到安裝包的方法步驟

    C#打包部署并把.net framework框架打到安裝包的方法步驟

    打包c#程序時,有時需要添加.net framework組件到安裝包,本文就來介紹一下C#打包部署并把.net framework框架打到安裝包的方法步驟,具有一定的參考價值,感興趣的可以了解一下
    2023-10-10
  • 使用C#編寫自己的區(qū)塊鏈挖礦算法

    使用C#編寫自己的區(qū)塊鏈挖礦算法

    這篇文章主要介紹了使用C#編寫自己的區(qū)塊鏈挖礦算法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08

最新評論