/*********************************************************** **项目名称: **功能描述: 工作单元服务于仓储,并在工作单元中初始化上下文,为仓储单元提供上下文对象,由此确保同一上下文对象。 ************************************************************/ namespace BZPT.Repositories { using Autofac; using Microsoft.Extensions.Logging; using NPlatform.DI; using BZPT.Domains.Entity; using BZPT.Domains.IRepositories; using NPlatform.Filters; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using NPlatform.Repositories.IRepositories; using SqlSugar; /// /// IUnitOfWork 的实现,实现事务功能。 /// public class UnitOfWorkSugar : IDisposable, IUnitOfWorkSugar { protected DBContext? _dbContext; public IRepositoryOptions Options { get; set; } /// /// Initializes a new instance of the class. /// IUnitOfWork /// /// /// EFContext /// public UnitOfWorkSugar(IRepositoryOptions options, DBContext db) { Options = options; _dbContext = db; } public T GetRepository() where T :class { var result = IOCService.Container.Resolve(new TypedParameter(typeof(IRepositoryOptions), Options), new TypedParameter(typeof(IRepositoryOptions), _dbContext)); return result; } /// /// 是否开启了事务 /// public bool BeginTrans { get; set; } /// /// 获取 当前单元操作是否已被提交 /// public bool IsCommitted { get; private set; } /// /// 连接超时设定 /// public int? Timeout { get; set; } /// /// 提交所有工作 /// public virtual void BeginTran() { _dbContext?.BeginTran(); BeginTrans = true; } /// /// 提交所有工作 /// public virtual void Commit() { if (IsCommitted) { return; } try { _dbContext?.CommitTran(); IsCommitted = true; } catch (Exception e) { if (e.InnerException != null) { Console.WriteLine(e.InnerException.ToString()); throw e.InnerException; } throw; } } /// /// 对象销毁是提交任务 /// public void Dispose() { if (this._dbContext != null) { System.Diagnostics.Debug.WriteLine($"{(_dbContext as object).GetHashCode()} | TransConn 销毁"); } if (BeginTrans && !IsCommitted) { Commit(); } try { _dbContext?.Dispose(); } catch { // ignored } if (_dbContext != null) { _dbContext.Dispose(); } this._dbContext = null; try { GC.SuppressFinalize(this); } catch { // i } } /// /// 回滚事物 /// public virtual void Rollback() { if (IsCommitted) { return; } try { this._dbContext?.RollbackTran(); IsCommitted = true; } catch (Exception e) { if (e.InnerException != null) { Console.WriteLine(e.InnerException.ToString()); throw e.InnerException; } throw; } } } }