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