一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - C# - 利用AOP實(shí)現(xiàn)SqlSugar自動事務(wù)

利用AOP實(shí)現(xiàn)SqlSugar自動事務(wù)

2022-01-25 14:08若若若邪 C#

這篇文章主要為大家詳細(xì)介紹了利用AOP實(shí)現(xiàn)SqlSugar自動事務(wù),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了如何利用AOP實(shí)現(xiàn)SqlSugar自動事務(wù),供大家參考,具體內(nèi)容如下

先看一下效果,帶接口層的三層架構(gòu):

BL層:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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;
    }
  }

假設(shè)GetStudentList方法里的mStudentDa.GetStudents和mValueService.FindAll不是查詢操作,而是更新操作,當(dāng)一個失敗另一個需要回滾,就需要在同一個事務(wù)里,當(dāng)一個出現(xiàn)異常就要回滾事務(wù)。

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

DA層:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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做一下包裝

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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, //默認(rèn)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("內(nèi)部錯誤: SqlSugarClient已丟失.");
      }
      return id;
    }
 
    public static void BeginTran()
    {
      var instance=GetInstance();
      //開啟事務(wù)
      if (!instance.IsBeginTran)
      {
        instance.SqlSugarClient.Ado.BeginTran();
        instance.IsBeginTran = true;
      }
    }
 
    public static void CommitTran()
    {
      var id = GetId();
      if (!_cache.ContainsKey(id))
        throw new Exception("內(nèi)部錯誤: 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("內(nèi)部錯誤: 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("內(nèi)部錯誤: SqlSugarClient已丟失.");
      _cache[id].TranCount++;
    }
    public static void TranCountMunisOne()
    {
      var id = GetId();
      if (!_cache.ContainsKey(id))
        throw new Exception("內(nèi)部錯誤: SqlSugarClient已丟失.");
      _cache[id].TranCount--;
    }
  }

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

不知道SqlSugar判斷當(dāng)前實(shí)例是否已經(jīng)開啟事務(wù),所以又將SqlSugar包了一層。

?
1
2
3
4
5
6
7
8
9
10
11
public class SqlClient
  {
    public SqlSugarClient SqlSugarClient;
    public bool IsBeginTran = false;
    public int TranCount = 0;
 
    public SqlClient(SqlSugarClient sqlSugarClient)
    {
      this.SqlSugarClient = sqlSugarClient;
    }
  }

IsBeginTran標(biāo)識當(dāng)前SqlSugar實(shí)例是否已經(jīng)開啟事務(wù),TranCount是一個避免事務(wù)嵌套的計(jì)數(shù)器。

一開始的例子

?
1
2
3
4
5
6
7
[TransactionCallHandler]
     public IList<Student> GetStudentList(Hashtable paramsHash)
     {
       var list = mStudentDa.GetStudents(paramsHash);
       var value = mValueService.FindAll();
       return list;
     }

TransactionCallHandler表明該方法要開啟事務(wù),但是如果mValueService.FindAll也標(biāo)識了TransactionCallHandler,又要開啟一次事務(wù)?所以用TranCount做一個計(jì)數(shù)。

使用Castle.DynamicProxy

要實(shí)現(xiàn)標(biāo)識了TransactionCallHandler的方法實(shí)現(xiàn)自動事務(wù),使用Castle.DynamicProxy實(shí)現(xiàn)BL類的代理

Castle.DynamicProxy一般操作

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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就是要開啟事務(wù)的地方,after就是提交事務(wù)的地方

最后實(shí)現(xiàn)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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結(jié)合使用

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

?
1
proxyGenerate.CreateClassProxy<MyClass>(t);

而且項(xiàng)目里BL類的實(shí)例化是交給IOC容器控制的,我用的是Autofac。當(dāng)然Autofac和Castle.DynamicProxy是可以結(jié)合使用的

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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>();
    }
  }

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://www.cnblogs.com/jaycewu/archive/2017/10/25/7733114.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产婷婷高清在线观看免费 | 好爽好深好猛好舒服视频上 | 免费国产高清精品一区在线 | 99热这里只有精品久久免费 | 日韩性事 | 人禽l交视频在线播放 视频 | 亚洲一级特黄特黄的大片 | 日韩欧美一区二区三区四区 | 国产欧美日韩不卡一区二区三区 | 久久综合给合久久狠狠狠… | 九九99在线视频 | 狠狠色婷婷狠狠狠亚洲综合 | 欧美猛男同志video在线 | 亚洲精品在线网址 | 精品成人片深夜 | 色哺乳妇hd | 国产资源视频在线观看 | 亚洲视频一区二区在线观看 | 日本精品中文字幕在线播放 | 亚洲欧美日韩另类精品一区二区三区 | 公交车揉捏大乳呻吟喘娇 | 国产欧美日韩精品高清二区综合区 | 成人在线视频观看 | 日本人和黑人一级纶理片 | 欧美人与牲动交xxx 欧美人妖另类性hd 欧美人人干 | 久久久无码精品无码国产人妻丝瓜 | 全色黄大色黄大片爽一次 | 91大神大战高跟丝袜美女 | 国产精品久久久久久久久ktv | 色综合久久综合网欧美综合网 | 午夜精品久久久久久久99蜜桃i | 国产91网站在线观看 | 喜马拉雅听书免费版 | 2021最新国产成人精品视频 | 王的视频vk | 爱草影院| 毛片a区| www.国产在线观看 | 国产精品国产国产aⅴ | 四虎新网址 | 青草青青在线视频观看 |