开发人员只需要在GRPC层简单调用即可实现CURD业务 。
public async override Task<AddProductReply> AddProduct(AddProductRequest request, ServerCallContext context){CUDCommand<AddProductRequest> addProductCommand = new CUDCommand<AddProductRequest>();addProductCommand.Id = Guid.NewGuid();addProductCommand.Model = request;addProductCommand.Operation = "C";await _mediator.Send(addProductCommand);return new AddProductReply(){Message = "Add Product sucess"};}10. 业务实体验证通过FluentValidation和MediatR 管道实现业务实体自动验证,并自动抛出自定义异常 。

文章插图

文章插图
public class RequestValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>{private readonly IEnumerable<IValidator<TRequest>> _validators;public RequestValidationBehavior(IEnumerable<IValidator<TRequest>> validators){_validators = validators;}public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next){var errors = _validators.Select(v => v.Validate(request)).SelectMany(result => result.Errors).Where(error => error != null).ToList();if (errors.Any()){var errorBuilder = new StringBuilder();errorBuilder.AppendLine("Invalid Request, reason: ");foreach (var error in errors){errorBuilder.AppendLine(error.ErrorMessage);}throw new InvalidRequestException(errorBuilder.ToString(), null);}return await next();}}开发人员只需要定义验证规则即可
public class AddCategoryCommandValidator : AbstractValidator<AddCategoryCommand>{public AddCategoryCommandValidator(){RuleFor(x => x.Model.CategoryName).NotEmpty().WithMessage(p => "类别名称不能为空.");}}11.请求日志和性能日志记录基于MediatR 管道实现请求日志和性能日志记录 。

文章插图

文章插图
public class RequestPerformanceBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse>{private readonly Stopwatch _timer;private readonly ILogger<TRequest> _logger;private readonly ICurrentUserService _currentUserService;private readonly ICurrentTenantService _currentTenantService;public RequestPerformanceBehaviour(ILogger<TRequest> logger, ICurrentUserService currentUserService, ICurrentTenantService currentTenantService){_timer = new Stopwatch();_logger = logger;_currentUserService = currentUserService;_currentTenantService = currentTenantService;}public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next){_timer.Start();var response = await next();_timer.Stop();if (_timer.ElapsedMilliseconds > 500){var name = typeof(TRequest).Name;_logger.LogWarning("Request End: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}",name, _timer.ElapsedMilliseconds, _currentUserService.UserId, request);}return response;}}
经验总结扩展阅读
- 长期穿运动鞋的危害
- 太古行眼镜怎么样
- 烤生蚝的技巧
- 孩子太调皮好动怎么办
- 膝关节退行性变怎么办
- 树干涂白剂的配方是什么
- 我的 Kafka 旅程 - Consumer
- 油漆涂料怎么洗?
- 胡椒怎么种植?
- 大多数中小企业采用的租赁方式是什么?