Files
2026-10-08 10:43:59 +08:00

47 lines
1.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using FreeSql;
using F9WebAiTest.Application.Interfaces.UOW;
namespace F9WebAiTest.Infrastructure.FreeSqls.Persistence;
/// <summary>
/// 工作单元实现:基于 FreeSql 的 UnitOfWorkManager,事务内 Orm 通过 AsyncLocal 暴露给仓储。
/// 仓储通过 UnitOfWork.CurrentOrm 获取事务感知的 Orm。
/// </summary>
public class UnitOfWork_F9 : IUnitOfWork_F9
{
private readonly IFreeSql _fsql;
private readonly UnitOfWorkManager _uowManager;
private static readonly AsyncLocal<IFreeSql> _currentOrm = new();
/// <summary>当前事务内的 Orm(非事务上下文返回 null)</summary>
public static IFreeSql CurrentOrm => _currentOrm.Value;
public UnitOfWork_F9(IFreeSql fsql)
{
_fsql = fsql;
_uowManager = new UnitOfWorkManager(fsql);
}
public async Task<bool> ExecuteWithUow(Func<Task<bool>> func)
{
using var uow = _uowManager.Begin();
_currentOrm.Value = uow.Orm;
try
{
var result = await func();
if (result) uow.Commit();
else uow.Rollback();
return result;
}
catch
{
uow.Rollback();
throw;
}
finally
{
_currentOrm.Value = null;
}
}
}