- 增加 UnitOfWork.Current 静态属性,AsyncLocal 实现 [NETStandard 2.0];

This commit is contained in:
28810
2019-07-25 16:45:07 +08:00
parent f9600d6c76
commit fc84f68f3a
6 changed files with 69 additions and 228 deletions

View File

@ -2,11 +2,15 @@
using System;
using System.Data;
using System.Data.Common;
using System.Threading;
namespace FreeSql
{
class UnitOfWork : IUnitOfWork
public class UnitOfWork : IUnitOfWork
{
#if ns20
public static readonly AsyncLocal<IUnitOfWork> Current = new AsyncLocal<IUnitOfWork>();
#endif
protected IFreeSql _fsql;
protected Object<DbConnection> _conn;
@ -15,6 +19,9 @@ namespace FreeSql
public UnitOfWork(IFreeSql fsql)
{
_fsql = fsql;
#if ns20
Current.Value = this;
#endif
}
void ReturnObject()
@ -22,30 +29,20 @@ namespace FreeSql
_fsql.Ado.MasterPool.Return(_conn);
_tran = null;
_conn = null;
#if ns20
Current.Value = null;
#endif
}
/// <summary>
/// 是否启用工作单元
/// </summary>
public bool Enable { get; private set; } = true;
/// <summary>
/// 禁用工作单元
/// <exception cref="Exception"></exception>
/// <para></para>
/// 若已开启事务已有Insert/Update/Delete操作调用此方法将发生异常建议在执行逻辑前调用
/// </summary>
public void Close()
{
if (_tran != null)
{
throw new Exception("已开启事务,不能禁用工作单元");
}
Enable = false;
}
public void Open()
{
Enable = true;
@ -55,7 +52,6 @@ namespace FreeSql
public DbTransaction GetOrBeginTransaction(bool isCreate = true)
{
if (_tran != null) return _tran;
if (isCreate == false) return null;
if (!Enable) return null;
@ -78,30 +74,24 @@ namespace FreeSql
public void Commit()
{
if (_tran != null)
try
{
try
{
_tran.Commit();
}
finally
{
ReturnObject();
}
if (_tran != null) _tran.Commit();
}
finally
{
ReturnObject();
}
}
public void Rollback()
{
if (_tran != null)
try
{
try
{
_tran.Rollback();
}
finally
{
ReturnObject();
}
if (_tran != null) _tran.Rollback();
}
finally
{
ReturnObject();
}
}
~UnitOfWork()
@ -112,15 +102,10 @@ namespace FreeSql
public void Dispose()
{
if (_isdisposed) return;
try
{
this.Rollback();
}
finally
{
_isdisposed = true;
GC.SuppressFinalize(this);
}
_isdisposed = true;
this.Rollback();
this.Close();
GC.SuppressFinalize(this);
}
}
}