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>();

下一章学习:基于dapper的repository。