1.新建IUnitOfWork接口,定义保存更改方法和释放方法
namespace ET.BUA.Core.Abstraction.Uow
#region 简化版
public interface IUnitOfWork : IDisposable
{
int SaveChanges();
void Dispose(bool disposing);
}
#endregion
}
2.新建UnitOfWork类实现该接口
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
namespace ET.BUA.Core.Abstraction.Uow
{
#region 简化版
public class UnitOfWork<TDbContext> : IUnitOfWork where TDbContext : DbContext
{
#region Private Fields
private TDbContext _dbContext;
private bool _disposed;
private Dictionary<string, dynamic> _repositories;
#endregion Private Fields
#region 构造方法
public UnitOfWork(TDbContext context)
{
_dbContext = context ?? throw new ArgumentNullException(nameof(context));
_repositories = new Dictionary<string, dynamic>();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
if (_dbContext != null)
{
_dbContext.Dispose();
_dbContext = null;
}
}
_disposed = true;
}
#endregion
public int SaveChanges()
{
return _dbContext.SaveChanges();
}
public Task<int> SaveChangesAsync()
{
return _dbContext.SaveChangesAsync();
}
public Task<int> SaveChangesAsync(CancellationToken cancellationToken)
{
return _dbContext.SaveChangesAsync(cancellationToken);
}
}
#endregion
}
3.新建DI注入实现类UnitOfWorkServiceCollectionExtensions.cs
using ET.BUA.Core.Abstraction.Uow;
using Microsoft.EntityFrameworkCore;
namespace Microsoft.Extensions.DependencyInjection
{
#region 简化版
public static class UnitOfWorkServiceCollectionExtensions
{
public static IServiceCollection AddUnitOfWork<TContext>(this IServiceCollection services) where TContext : DbContext
{
services.AddScoped<IUnitOfWork, UnitOfWork<TContext>>();
return services;
}
}
#endregion
}
4.在StartUp.cs的ConfigureServices方法中进行注册,参数为数据库上下文实例
services.AddUnitOfWork<BUAContext>();
5.仓储层Repository不实现SaveChanges,由服务层Servcie注入UnitOfWork实现事务
using ET.BUA.Core.Abstraction.Uow;
using ET.BUA.Domain.Repository;
using ET.BUA.Entity.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ET.BUA.Service.Service.Implementation
{
public class ApplicationService : IApplicationService
{
private readonly IApplicationRepository _appRepo;
private readonly IUnitOfWork _unitOfWork;
public ApplicationService(
IApplicationRepository appRepo,
IUnitOfWork unitOfWork)
{
_appRepo = appRepo ?? throw new ArgumentNullException(nameof(appRepo));
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public void Add(ApplicationEntity app)
{
_appRepo.Insert(app);
_unitOfWork.SaveChanges();
}
public async Task<ApplicationEntity> GetSingleModelAsync(string Code)
{
return await _appRepo.FirstOrDefaultAsync(c => c.APP_CODE==Code);
}
public ApplicationEntity GetSingleModel(string Code)
{
return _appRepo.FirstOrDefault(c => c.APP_CODE == Code);
}
}
}