(精华)2020年9月20日 ASP.NET Core MediatR进程内的消息通信框架的使用

MediatR介绍

.NET中的简单中介者模式实现,一种进程内消息传递机制(无其他外部依赖)。 支持以同步或异步的形式进行请求/响应,命令,查询,通知和事件的消息传递,并通过C#泛型支持消息的智能调度。
首先引入两个类库

MediatR
MediatR.Extensions.Microsoft.DependencyInjection

第一种使用方式:CQRS

Handlers

public class MakeOrderCommandHandler : IRequestHandler<MakeOrderRequestModel,MakeOrderResponseModel>
{

    public Task<MakeOrderResponseModel> Handle(MakeOrderRequestModel request, CancellationToken cancellationToken)
    {
        var result = new MakeOrderResponseModel
        {
            IsSuccess = true,
            OrderId = new Guid("53d26807-ad70-4449-8479-024c54eb2020")
        };

        // 业务逻辑

        return Task.FromResult(result);
    }
}
public class GetOrderByIdQueryHandler : IRequestHandler<GetOrderByIdRequestModel, GetOrderByIdResponseModel>
{

    public Task<GetOrderByIdResponseModel> Handle(GetOrderByIdRequestModel request, CancellationToken cancellationToken)
    {
        var orderDetails = new GetOrderByIdResponseModel();
        // 业务逻辑
        return Task.FromResult(orderDetails);
    }
}

RequestModels

public class MakeOrderRequestModel : IRequest<MakeOrderResponseModel>
{
    public Guid OrderId { get; set; }
    public string OrderName { get; set; }
    public DateTime DateOrder { get; set; }
    public Guid ProductId { get; set; }
    public int Quantity { get; set; }
    public double Amount { get; set; }
    public Guid OrderPersonId { get; set; }
}
public class GetOrderByIdRequestModel : IRequest<GetOrderByIdResponseModel>
{
    public Guid OrderId { get; set; }
}

ResponseModels

public class MakeOrderResponseModel
{
    public bool IsSuccess { get; set; }
    public Guid OrderId { get; set; }
}
public class GetOrderByIdResponseModel
{
    public Guid OrderId { get; set; }
    public string OrderName { get; set; }
    public DateTime DateOrder { get; set; }
    public Guid ProductId { get; set; }
    public int Quantity { get; set; }
    public double Amount { get; set; }
    public Guid OrderPersonId { get; set; }
    public string ProductName { get; set; }
    public string OrderPersonName { get; set; }

}

注入

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddMediatR(Assembly.GetExecutingAssembly());
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

使用

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

    public OrderController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public IActionResult MakeOrder([FromBody] MakeOrderRequestModel requestModel)
    {
        var response = _mediator.Send(requestModel).Result;
        return Ok(response);
    }

    [HttpGet]
    public IActionResult OrderDetails(Guid id)
    {
        var response = _mediator.Send(new GetOrderByIdRequestModel {OrderId = id}).Result;
        return Ok(response);
    }
}

第二种使用方式:发布订阅模式

Handlers

public class GeneralNotificationHandler : INotificationHandler<GeneralNotificationModel>
{
    public Task Handle(GeneralNotificationModel notification, CancellationToken cancellationToken)
    {
        Console.WriteLine($"{notification.Title}:{notification.Content}");
        return Task.CompletedTask;
    }
}
public class LogHandler : INotificationHandler<GeneralNotificationModel>
{
    private readonly ILogger<LogHandler> _logger;

    public LogHandler(ILogger<LogHandler> logger)
    {
        _logger = logger;
    }

    public Task Handle(GeneralNotificationModel notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation($"{notification.Title}:{notification.Content}");
        return Task.CompletedTask;
    }
}

NotificationModels

public class GeneralNotificationModel : INotification
{
    public string Title { get; set; }
    public string Content { get; set; }

    public GeneralNotificationModel(string title, string content)
    {
        Title = title;
        Content = content;
    }
}

使用

public class MakeOrderCommandHandler : IRequestHandler<MakeOrderRequestModel,MakeOrderResponseModel>
{
    private readonly IMediator _mediator;

    public MakeOrderCommandHandler(IMediator mediator)
    {
        _mediator = mediator;
    }

    public Task<MakeOrderResponseModel> Handle(MakeOrderRequestModel request, CancellationToken cancellationToken)
    {
        var result = new MakeOrderResponseModel
        {
            IsSuccess = true,
            OrderId = new Guid("53d26807-ad70-4449-8479-024c54eb2020")
        };
        //发布
        _mediator.Publish(new GeneralNotificationModel("已下单", result.OrderId.ToString()), cancellationToken);

        return Task.FromResult(result);
    }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 猿与汪的秘密 设计师:上身试试 返回首页