/*********************************************************** **项目名称: **功能描述: 工作单元服务于仓储,并在工作单元中初始化上下文,为仓储单元提供上下文对象,由此确保同一上下文对象。 ************************************************************/ 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; /// /// IUnitOfWork 的实现,实现事务功能。 /// public class UnitOfWork : IDisposable { protected DBContext? _dbContext; public IRepositoryOptions Options { get; set; } /// /// Initializes a new instance of the class. /// IUnitOfWork /// /// /// EFContext /// public UnitOfWork(IRepositoryOptions options, DBContext db) { Options = options; _dbContext = db; _dbContext.BeginTran(); BeginTrans = true; } public T GetRepository() where T: class { var result = IOCService.Container.Resolve(); return result; } /// /// 是否开启了事务 /// public bool BeginTrans { get; } /// /// 获取 当前单元操作是否已被提交 /// public bool IsCommitted { get; private set; } /// /// 连接超时设定 /// public int? Timeout { get; set; } /// /// 设置实体的过滤器属性 /// /// 实体 private void SetFilter(IEnumerable items) where T : class, IEntity { // 实体如果实现了过滤器, 那么仓储就可以拿注入进来的过滤器对实体进行设置与过滤。 if (typeof(IFilter).IsAssignableFrom(typeof(T))) { foreach(var entity in items) { foreach (var filter in this.Options.QueryFilters) { filter.Value.SetFilterProperty(entity); // 设置过滤器 } } } } /// /// 提交所有工作 /// 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; } } } }