using Microsoft.Extensions.Logging;
|
using SqlSugar;
|
using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace WIDESEA_Core.BaseRepository
|
{
|
public class UnitOfWork : IDisposable
|
{
|
// 定义一个ILogger类型的Logger属性
|
public ILogger Logger { get; set; }
|
// 定义一个ISqlSugarClient类型的Db属性
|
public ISqlSugarClient Db { get; internal set; }
|
|
// 定义一个ITenant类型的Tenant属性
|
public ITenant Tenant { get; internal set; }
|
|
// 定义一个bool类型的IsTran属性,表示是否开启事务
|
public bool IsTran { get; internal set; }
|
|
// 定义一个bool类型的IsCommit属性,表示是否提交事务
|
public bool IsCommit { get; internal set; }
|
|
// 定义一个bool类型的IsClose属性,表示是否关闭连接
|
public bool IsClose { get; internal set; }
|
|
// 实现IDisposable接口的Dispose方法
|
public void Dispose()
|
{
|
// 如果开启事务且未提交事务,则回滚事务
|
if (IsTran && !IsCommit)
|
{
|
Logger.LogDebug("UnitOfWork RollbackTran");
|
this.Tenant.RollbackTran();
|
}
|
|
// 如果事务不为空或者已经关闭连接,则直接返回
|
if (this.Db.Ado.Transaction != null || this.IsClose)
|
return;
|
// 关闭连接
|
this.Db.Close();
|
}
|
|
// 提交事务
|
public bool Commit()
|
{
|
// 如果开启事务且未提交事务,则提交事务
|
if (this.IsTran && !this.IsCommit)
|
{
|
Logger.LogDebug("UnitOfWork CommitTran");
|
this.Tenant.CommitTran();
|
this.IsCommit = true;
|
}
|
|
// 如果事务为空且未关闭连接,则关闭连接
|
if (this.Db.Ado.Transaction == null && !this.IsClose)
|
{
|
this.Db.Close();
|
this.IsClose = true;
|
}
|
|
// 返回是否提交事务
|
return this.IsCommit;
|
}
|
}
|
}
|