工业上位机项目的完整 MediatR 管道行为(Pipeline Behaviors)示例代码

发布时间:2026/9/18 0:29:10
工业上位机项目的完整 MediatR 管道行为(Pipeline Behaviors)示例代码 ** 工业上位机项目的完整 MediatR 管道行为Pipeline Behaviors示例代码**包含工业级推荐的 4 个核心 Behavior。1. 标记接口推荐使用// MaxWell.Application/CQRS/Base/ICommand.cspublicinterfaceICommandoutTResponse:IRequestTResponse{}// MaxWell.Application/CQRS/Base/IQuery.cspublicinterfaceIQueryoutTResponse:IRequestTResponse{}// MaxWell.Application/CQRS/Base/ITransactionalCommand.cspublicinterfaceITransactionalCommand{}// 需要事务的 Command 实现此接口2. 完整管道行为代码Behavior 1验证行为ValidationBehavior// MaxWell.Application/Behaviors/ValidationBehavior.csusingFluentValidation;usingMediatR;usingSystem.Linq;namespaceMaxWell.Application.Behaviors;publicclassValidationBehaviorTRequest,TResponse:IPipelineBehaviorTRequest,TResponsewhereTRequest:IRequestTResponse{privatereadonlyIEnumerableIValidatorTRequest_validators;publicValidationBehavior(IEnumerableIValidatorTRequestvalidators){_validatorsvalidators;}publicasyncTaskTResponseHandle(TRequestrequest,RequestHandlerDelegateTResponsenext,CancellationTokenct){if(_validatorsnull||!_validators.Any())returnawaitnext();varcontextnewValidationContextTRequest(request);varvalidationResultsawaitTask.WhenAll(_validators.Select(vv.ValidateAsync(context,ct)));varfailuresvalidationResults.SelectMany(rr.Errors).Where(ff!null).ToList();if(failures.Count0){varerrorMessagestring.Join(Environment.NewLine,failures.Select(ff.ErrorMessage));thrownewValidationException($命令验证失败{errorMessage});}returnawaitnext();}}Behavior 2日志 性能监控行为// MaxWell.Application/Behaviors/LoggingAndPerformanceBehavior.csusingMediatR;usinglog4net;usingSystem.Diagnostics;usingSystem.Text.Json;namespaceMaxWell.Application.Behaviors;publicclassLoggingAndPerformanceBehaviorTRequest,TResponse:IPipelineBehaviorTRequest,TResponsewhereTRequest:IRequestTResponse{privatestaticreadonlyILog_loggerLogManager.GetLogger(MediatR);publicasyncTaskTResponseHandle(TRequestrequest,RequestHandlerDelegateTResponsenext,CancellationTokenct){varrequestNametypeof(TRequest).Name;varswStopwatch.StartNew();try{_logger.Info($[MediatR START]{requestName}|{JsonSerializer.Serialize(request)});varresponseawaitnext();sw.Stop();varsuccessresponseisHardwareResulthr?hr.IsSuccess.ToString():OK;_logger.Info($[MediatR END]{requestName}| Success:{success}| 耗时:{sw.ElapsedMilliseconds}ms);returnresponse;}catch(Exceptionex){sw.Stop();_logger.Error($[MediatR ERROR]{requestName}| 耗时:{sw.ElapsedMilliseconds}ms,ex);throw;}}}Behavior 3事务行为仅针对需要事务的命令// MaxWell.Application/Behaviors/TransactionBehavior.csusingMediatR;usingMaxWell.Infrastructure.Persistence;namespaceMaxWell.Application.Behaviors;publicclassTransactionBehaviorTRequest,TResponse:IPipelineBehaviorTRequest,TResponsewhereTRequest:IRequestTResponse{privatereadonlyAppDbContext_dbContext;publicTransactionBehavior(AppDbContextdbContext){_dbContextdbContext;}publicasyncTaskTResponseHandle(TRequestrequest,RequestHandlerDelegateTResponsenext,CancellationTokenct){// 只对标记了 ITransactionalCommand 的命令启用事务if(requestisnotITransactionalCommand)returnawaitnext();awaitusingvartransactionawait_dbContext.Database.BeginTransactionAsync(ct);try{varresponseawaitnext();awaittransaction.CommitAsync(ct);returnresponse;}catch(Exception){awaittransaction.RollbackAsync(ct);throw;}}}Behavior 4异常统一处理 短路行为可选增强// MaxWell.Application/Behaviors/ExceptionHandlingBehavior.cspublicclassExceptionHandlingBehaviorTRequest,TResponse:IPipelineBehaviorTRequest,TResponsewhereTRequest:IRequestTResponse{privatestaticreadonlyILog_loggerLogManager.GetLogger(MediatR.Exception);publicasyncTaskTResponseHandle(TRequestrequest,RequestHandlerDelegateTResponsenext,CancellationTokenct){try{returnawaitnext();}catch(ValidationExceptionvex){_logger.Warn($验证失败:{typeof(TRequest).Name},vex);throw;}catch(Exceptionex){_logger.Error($执行命令时发生未处理异常:{typeof(TRequest).Name},ex);if(typeof(TResponse)typeof(HardwareResult)){return(TResponse)(object)HardwareResult.Fail($系统异常:{ex.Message});}throw;}}}5. 在 App.xaml.cs 中注册关键protectedoverridevoidRegisterTypes(IContainerRegistrycontainerRegistry){varservicesnewServiceCollection();// ... 其他注册DbContext、DeviceManager 等services.AddMediatR(cfg{cfg.RegisterServicesFromAssembly(typeof(StartExperimentCommand).Assembly);});// 管道行为注册顺序非常重要由外到内services.AddTransient(typeof(IPipelineBehavior,),typeof(ValidationBehavior,));services.AddTransient(typeof(IPipelineBehavior,),typeof(ExceptionHandlingBehavior,));services.AddTransient(typeof(IPipelineBehavior,),typeof(LoggingAndPerformanceBehavior,));services.AddTransient(typeof(IPipelineBehavior,),typeof(TransactionBehavior,));_serviceProviderservices.BuildServiceProvider();containerRegistry.RegisterInstance(_serviceProvider);}使用效果当执行以下代码时varresultawait_mediator.Send(newStartExperimentCommand(...));会依次经过验证 → 2. 异常处理 → 3. 日志记录 → 4. 事务如果需要→ Handler → 后置日志推荐ValidationBehavior放在最外层ExceptionHandlingBehavior紧随其后Logging放在中间Transaction放在最内层接近业务

关于本文作者

来自尧图内容编辑团队

尧图内容编辑团队 内容团队

尧图内容编辑团队

本文由尧图网络内容编辑团队执笔。团队由资深项目经理、前端工程师与设计师组成,所有内容均来自亲手交付的真实项目,先讲清问题、再给出可落地的解法。尧图深耕北京网站建设十年,服务过京华建材集团、智造科技等各行业客户,把一线经验沉淀为可复用的行业观察。

  • 十年建站经验,覆盖建材、制造、服务、文创等
  • 项目经理把关选题与事实准确性
  • 工程师与设计师联合撰写专业细节
  • 统一编辑规范,保证文风与排版一致
  • 每月复盘转化数据,迭代选题方向

延伸阅读

相关资讯与近期热门内容

深度阅读推荐

建站决策前值得细读的三篇

网站改版的5个关键决策
2024-08-12

网站改版的5个关键决策

什么时候该改版、改到什么程度、如何避免流量掉光,京华建材集团改版复盘给出答案。

获取专属建站方案

看完文章,把您的行业与预算告诉我们,免费获取一份量身定制的官网建设方案与报价。

立即免费咨询