TemplatePro/BZPT.SqlSugarRepository/UnitOfWork.cs

183 lines
4.8 KiB
C#

/***********************************************************
**项目名称:
**功能描述:
工作单元服务于仓储,并在工作单元中初始化上下文,为仓储单元提供上下文对象,由此确保同一上下文对象。
************************************************************/
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;
/// <summary>
/// IUnitOfWork 的实现,实现事务功能。
/// </summary>
public class UnitOfWork : IDisposable
{
protected DBContext? _dbContext;
public IRepositoryOptions Options { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="RepositoryBase{TEntity,TPrimaryKey}"/> class.
/// IUnitOfWork
/// </summary>
/// <param name="option">
/// EFContext
/// </param>
public UnitOfWork(IRepositoryOptions options, DBContext db)
{
Options = options;
_dbContext = db;
_dbContext.BeginTran();
BeginTrans = true;
}
public T GetRepository<T>() where T: class
{
var result = IOCService.Container.Resolve<T>();
return result;
}
/// <summary>
/// 是否开启了事务
/// </summary>
public bool BeginTrans { get; }
/// <summary>
/// 获取 当前单元操作是否已被提交
/// </summary>
public bool IsCommitted { get; private set; }
/// <summary>
/// 连接超时设定
/// </summary>
public int? Timeout { get; set; }
/// <summary>
/// 设置实体的过滤器属性
/// </summary>
/// <param name="items">实体</param>
private void SetFilter<T>(IEnumerable<T> 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<T>(entity); // 设置过滤器
}
}
}
}
/// <summary>
/// 提交所有工作
/// </summary>
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;
}
}
/// <summary>
/// 对象销毁是提交任务
/// </summary>
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
}
}
/// <summary>
/// 回滚事物
/// </summary>
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;
}
}
}
}