MediatR基础用法(事件)
MediatR基础使用:
1.在WebAPI或者Asp.netCore项目中添加MediatR
PM=> Install-Package MediatR.Extensions.Microsoft.DependencyInjection
builder.Services.AddMediatR(Assembly.GetExecutingAssembly());
2.声明一个传输对象:实现:INotification
public class SendData:INotification { public string UserName { get; set; } public string Content { get; set; } public override string ToString() { return $"用户名:{UserName}。传输内容:{Content}"; } }
3.在Controller中 构造注入IMediator 并在Action中发布 mediator.Publish(传输对象)
[Route("api/[controller]")] [ApiController] public class MadiatRController : ControllerBase { private IMediator mediator; public MadiatRController(IMediator mediator) { this.mediator = mediator; } [HttpGet("Test")] public string GetString() { mediator.Publish(new SendData() { UserName = "MadiatRController", Content = "GetString()" }); return "OK"; } }
4.添加事件处理类 继承 : NotificationHandler<传输对象>
public class OtherProcess : NotificationHandler{ protected override void Handle(SendData notification) { Console.WriteLine($"{nameof(OtherProcess) } {notification.ToString()}"); } } public class EventProcess : NotificationHandler { protected override void Handle(SendData notification) { Console.WriteLine($"{nameof(EventProcess) } {notification.ToString()}"); } }
5.调用API接口:
查看控制台: