MediatR基础用法(事件)

MediatR基础使用:

1.在WebAPI或者Asp.netCore项目中添加MediatR  

   PM=>    Install-Package MediatR.Extensions.Microsoft.DependencyInjection

  builder.Services.AddMediatR(Assembly.GetExecutingAssembly());

2.声明一个传输对象:实现:INotification

1
2
3
4
5
6
7
8
9
10
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(传输对象)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[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<传输对象>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class OtherProcess : NotificationHandler<SendData>
   {
       protected override void Handle(SendData notification)
       {
           Console.WriteLine($"{nameof(OtherProcess) } {notification.ToString()}");
       }
   }
 
 
   public class EventProcess : NotificationHandler<SendData>
   {
       protected override void Handle(SendData notification)
       {
           Console.WriteLine($"{nameof(EventProcess) } {notification.ToString()}");
       }
   }

  5.调用API接口:

查看控制台:

 

 

 

 

 

 

posted @   后跳  阅读(392)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示