Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.
Unit of Work --Martin Fowler
Unit Of Work模式,由馬丁大叔提出,是一種資料訪問模式,UOW模式的作用是在業務用例的操作中跟蹤物件的所有更改(增加、洗掉和更新),并將所有更改的物件保存在其維護的串列中,在業務用例的終點,通過事務,一次性提交所有更改,以確保資料的完整性和有效性,總而言之,UOW協調這些物件的持久化及并發問題,
定義作業單元介面:
1 /// <summary> 2 /// 作業單元介面 3 /// </summary> 4 public interface IUnitOfWork : IDisposable 5 { 6 /// <summary> 7 /// 事務 8 /// </summary> 9 IDbTransaction DbTransaction { get; } 10 /// <summary> 11 /// 資料連接 12 /// </summary> 13 IDbConnection DbConnection { get; } 14 15 /// <summary> 16 /// 開啟事務 17 /// </summary> 18 void BeginTransaction(); 19 /// <summary> 20 /// 完成事務 21 /// </summary> 22 void Commit(); 23 /// <summary> 24 /// 回滾事務 25 /// </summary> 26 void Rollback(); 27 }
實作作業單元:
1 /// <summary> 2 /// 作業單元 3 /// </summary> 4 public class UnitOfWork : IUnitOfWork 5 { 6 private bool _disposed; 7 private IDbTransaction _trans = null; 8 /// <summary> 9 /// 事務 10 /// </summary> 11 public IDbTransaction DbTransaction { get { return _trans; } } 12 13 private IDbConnection _connection; 14 /// <summary> 15 /// 資料連接 16 /// </summary> 17 public IDbConnection DbConnection { get { return _connection; } } 18 19 public UnitOfWork(IConfiguration configuration) 20 { 21 var connectionString = configuration.GetConnectionString("SqlConnection"); 22 _connection = new MySqlConnection(connectionString); //這里使用的mysql 23 _connection.Open(); 24 } 25 26 /// <summary> 27 /// 開啟事務 28 /// </summary> 29 public void BeginTransaction() 30 { 31 _trans = _connection.BeginTransaction(); 32 } 33 /// <summary> 34 /// 完成事務 35 /// </summary> 36 public void Commit() => _trans?.Commit(); 37 /// <summary> 38 /// 回滾事務 39 /// </summary> 40 public void Rollback() => _trans?.Rollback(); 41 42 public void Dispose() 43 { 44 Dispose(true); 45 GC.SuppressFinalize(this); 46 } 47 48 ~UnitOfWork() => Dispose(false); 49 50 protected virtual void Dispose(bool disposing) 51 { 52 if (_disposed) 53 return; 54 if (disposing) 55 { 56 _trans?.Dispose(); 57 _connection?.Dispose(); 58 } 59 _trans = null; 60 _connection = null; 61 _disposed = true; 62 } 63 }
在IServiceCollection容器中注冊:
services.AddScoped<IUnitOfWork, UnitOfWork>();
原始碼地址:https://github.com/letnet/NetCoreDemo
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/79150.html
標籤:.NET Core
上一篇:asp.net core 3.0 JObject The collection type 'Newtonsoft.Json.Linq.JObject' is not supported
下一篇:C#編程
