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

{ public Task Handle(OrderCreateCommand notification, CancellationToken cancellationToken) { Console.WriteLine("4444444——————————————第四个操作呢!"); return Task.CompletedTask; } } ///

/// 创建订单后处理步骤5 /// public class OrderCreateFiveHandler : INotificationHandler { public Task Handle(OrderCreateCommand notification, CancellationToken cancellationToken) { Console.WriteLine("55555——————————————接着奏乐接着舞!"); return Task.CompletedTask; } }} 注意:这里是用mediator的publish方法的实现的 , 命令查询类继承INotification就要用publish方法,继承IRequest就要用Send方法,项目目录也在左侧这样别人看着也清晰点
Asp.Net Core6.0中MediatR的应用CQRS

文章插图
7、IPipelineBehavior这个接口的作用就是在我们命令处理之前或者之后插入逻辑 , 类似我们的中间件,我新建一个TransactionBehavior来处理保存数据库之前之后的操作,这里的代码只判断了是否为空之前写的是判断事务是否为空,代码多就随便写了意思意思 。
然后新建一个DBTransactionBehavior这里对操作数据库新增演示一下
using MediatR;using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Metadata.Internal;namespace MediatApi.Helper{    public class TransactionBehavior<TDBContext, TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse> where TDBContext : WyyDbContext    {        ILogger _logger;        WyyDbContext _dbContext;        public TransactionBehavior(ILogger logger, WyyDbContext dbContext)        {            _logger = logger ?? throw new ArgumentNullException(nameof(logger));            _dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));        }        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)        {            var response = default(TResponse);            try            {                Console.WriteLine("执行前逻辑++++++++++++++++++++++++++++++++++");                Console.WriteLine();                if (request != null)                 return await next();                Console.WriteLine("逻辑不对处理++++++++++++++++++++++++++++++++");                Console.WriteLine();                var strategy = _dbContext.Database.CreateExecutionStrategy();                await strategy.ExecuteAsync(async () =>                {                    Guid transactionId;                    using (var transaction = await _dbContext.Database.BeginTransactionAsync())                    using (_logger.BeginScope("TransactionContext:{TransactionId}", transaction.TransactionId))                    {                        _logger.LogInformation("----- 开始事务 {TransactionId} 请求{request}", transaction.TransactionId, request);                        response = await next();                        _logger.LogInformation("----- 提交事务 {TransactionId}}", transaction.TransactionId);                        await _dbContext.CommitTransactionAsync(transaction);                        transactionId = transaction.TransactionId;                    }                });                return response;            }            catch(Exception ex)            {                _logger.LogError(ex, "处理事务出错{@Command}", request);                throw;            }        }    }}

推荐阅读