using Microsoft.Extensions.Logging;
using KH.WMS.Core.Database.Repositories;
using KH.WMS.Core.DependencyInjection.ServiceLifetimes;
namespace KH.WMS.Core.Database.UnitOfWorks;
///
/// 工作单元实现(面向接口,支持事务嵌套)
///
[RegisteredService(Lifetime = Microsoft.Extensions.DependencyInjection.ServiceLifetime.Scoped)]
public class UnitOfWork : IUnitOfWork
{
private readonly IDbContext _dbContext;
private readonly ILogger _logger;
private bool _disposed;
public UnitOfWork(IDbContext dbContext, ILogger logger)
{
_dbContext = dbContext;
_logger = logger;
}
///
/// 获取数据库上下文
///
public IDbContext DbContext => _dbContext;
///
/// 开始事务
///
public async Task BeginTransactionAsync(System.Data.IsolationLevel isolationLevel = System.Data.IsolationLevel.ReadCommitted)
{
await _dbContext.BeginTransactionAsync(isolationLevel);
_logger.LogDebug("工作单元事务已开启");
}
///
/// 提交事务
///
public async Task CommitAsync()
{
await _dbContext.CommitTransactionAsync();
_logger.LogDebug("工作单元事务已提交");
}
///
/// 回滚事务
///
public async Task RollbackAsync()
{
await _dbContext.RollbackTransactionAsync();
_logger.LogDebug("工作单元事务已回滚");
}
///
/// 获取仓储
///
public IRepository GetRepository() where T : class where TKey : struct
{
return _dbContext.GetRepository();
}
///
/// 执行 SQL 命令
///
public async Task ExecuteSqlAsync(string sql, params object?[] parameters) where TKey : struct
{
var repository = GetRepository();
// 使用 Ado 执行命令
// 这里需要根据实际的 ISqlSugarClient 实现来执行 SQL
return await Task.FromResult(0);
}
///
/// 执行 SQL 命令(返回列表)
///
public async Task> ExecuteSqlAsync(string sql, params object?[] parameters) where T : class where TKey : struct
{
var repository = GetRepository();
// 使用 Ado 执行查询
// 这里需要根据实际的 ISqlSugarClient 实现来执行 SQL
return await Task.FromResult(new List());
}
public void Dispose()
{
if (!_disposed)
{
_dbContext?.Dispose();
_disposed = true;
}
}
IRepository IUnitOfWork.GetRepository() where T : class where TKey : struct
{
return _dbContext.GetRepository();
}
}