打赏

CQRS MediatR中介者模式

CQRS MediatR中介者模式,这个讲的非常明白怎么用

MediatR
Install MediatR

PM> Install-Package MediatR

IMeditator
IRequese、IRequest
IRequestHandler<in TRequest, TResponse>

public class CreateOrderRequestModel:IRequest<string>
{
  public string UserId { get; set; }
  public string CardNumber { get; set; }
}
public class GetOrderByIdRequestModel:IRequest<string>
{
   public string OrderId { get; set; }
}

 

//返回值
public interface IRequest<out TResponse> : IBaseRequest{}
//无返回值
public interface IRequest : IRequest<Unit>, IBaseRequest{}

 



创建处理程序,所有的处理程序都通过IRequestHandler接口来实现,该接口有两个参数,第一个是请求内容,第二个是响应内容.

public class CreateOrderCommandHandler: IRequestHandler<CreateOrderRequestModel, string>
{
  public Task<string> Handle(CreateOrderRequestModel request, CancellationToken cancellationToken)
  {
    //do something...
    return Task.FromResult(request.UserId);
  }
}

 

正如下代码片段,处理程序实现了IRequestHandler带有输入和输出类型定义的接口

public interface IRequestHandler<in TRequest, TResponse> where TRequest : IRequest<TResponse>
{
   Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken);
}

public class GetOrderByIdQueryHandler :IRequestHandler<GetOrderByIdRequestModel, string>
{
   public Task<string> Handle(GetOrderByIdRequestModel request, CancellationToken cancellationToken)
   {
     //do something
     return Task.FromResult(request.OrderId);
    }
}

 



Install MediatR.Extensions.Microsoft.DependencyInjection

PM> MediatR.Extensions.Microsoft.DependencyInjection

在Startup.cs中注册MediatR

services.AddMediatR(Assembly.GetExecutingAssembly());

 

我们只需要注入IMediator接口,通过如下代码我们来使用他们

[Route("api/[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
   private readonly IMediator _mediator;
   public OrderController(IMediator mediator)
   {
      _mediator = mediator;
    }

   [HttpPost]
   public async Task<IActionResult> Post([FromBody]CreateOrderRequestModel requestModel)
   {
       var response =await _mediator.Send(requestModel);
        return Ok(response);
    }

   [HttpGet]
   public async Task<IActionResult> Get([FromQuery]GetOrderByIdRequestModel requestModel)
   {
       var response = await _mediator.Send(requestModel);
       return Ok(response);
    }
}

参考:https://blog.csdn.net/qq_27843785/article/details/105403630

posted @ 2022-02-16 18:00  刘奇云  阅读(76)  评论(0编辑  收藏  举报