Asp.Net Core6.0中MediatR的应用CQRS( 五 )

using MediatApi.Entity;using MediatR;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Storage;namespace MediatApi.Helper{    public class WyyDbContext: testContext    {        private IDbContextTransaction _currentTransaction;        public IDbContextTransaction GetCurrentTransaction() => _currentTransaction;        public bool HasActiveTransaction => _currentTransaction != null;        public async Task CommitTransactionAsync(IDbContextTransaction transaction)        {            if (transaction == null) throw new ArgumentNullException(nameof(transaction));            if (transaction != _currentTransaction) throw new InvalidOperationException($"Transaction {transaction.TransactionId} is not current");            try            {                await SaveChangesAsync();                transaction.Commit();            }            catch            {                RollbackTransaction();                throw;            }            finally            {                if (_currentTransaction != null)                {                    _currentTransaction.Dispose();                    _currentTransaction = null;                }            }        }        public void RollbackTransaction()        {            try            {                _currentTransaction?.Rollback();            }            finally            {                if (_currentTransaction != null)                {                    _currentTransaction.Dispose();                    _currentTransaction = null;                }            }        }    }}在Program里面注册服务
builder.Services.AddTransient(typeof(IPipelineBehavior<,>), typeof(DBTransactionBehavior<,>));这里链接数据库我们做一个新增Command里面的testContext就是数据库上下文我这里是从数据库直接生成的 WyyDbContext继承testContext
using MediatApi.Entity;using MediatR;namespace MediatApi.Application.Command{    public class CusCreateCommand:IRequest<int>    {        public string? Name { get; set; }        public int? Age { get; set; }    }    public class CusCreateCommandHandler : IRequestHandler<CusCreateCommand, int>    {        private readonly testContext _db;        public CusCreateCommandHandler(testContext db)        {            _db = db;        }        public async Task<int> Handle(CusCreateCommand request, CancellationToken cancellationToken)        {            Cu c = new()            {                Name = request.Name,                Age = request.Age,            };            _db.Cus.Add(c);            Console.WriteLine("执行处理++++++++++++++++++++++++++++++++++");            return await _db.SaveChangesAsync();        }    }}

推荐阅读