MediatR基本使用

发布时间 2023-11-12 20:52:25作者: LiXiang98

MediatR可以在进程内实现消息通信。

一、安装MediatR

程序包管理控制台执行以下代码:

dotnet add package MediatR --version 12.1.1

二、注册MediatR服务

services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
});

三、发送消息

await mediator.Publish(new UserPasswordChangeNotifaction(user.Name,user.Password));

UserPasswordChangeNotifaction是实现了INotifaction接口的类

 public record UserPasswordChangeNotifaction(string Name,string Password):INotification;

四、接收消息

HandelUserPasswordChange1和HandelUserPasswordChange2实现INotificationHandler接口

    public class HandelUserPasswordChange1 : INotificationHandler<UserPasswordChangeNotifaction>
    {
        public Task Handle(UserPasswordChangeNotifaction notification, CancellationToken cancellationToken)
        {
            Console.WriteLine($"HandelUserPasswordChange1:{notification.Name}修改密码为{notification.Password} {DateTime.Now}");
            return Task.CompletedTask;
        }
    }

    public class HandelUserPasswordChange2 : INotificationHandler<UserPasswordChangeNotifaction>
    {
        public Task Handle(UserPasswordChangeNotifaction notification, CancellationToken cancellationToken)
        {
            Console.WriteLine($"HandelUserPasswordChange2:{notification.Name}修改密码为{notification.Password} {DateTime.Now}");
            return Task.CompletedTask;
        }
    }

五、完整代码

ServiceCollection services = new ServiceCollection();
services.AddMediatR(cfg =>
{
    cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
});
using ServiceProvider sp = services.BuildServiceProvider();
using var scope = sp.CreateScope();
User user = new User("TestName", "111", "123456");
await user.ChangePassword("000000");
var mediator = scope.ServiceProvider.GetService<IMediator>();
await mediator.Publish(new UserPasswordChangeNotifaction(user.Name,user.Password));
Console.ReadLine();

User类代码;

public class User
{
	public int Id { get; set; }
	public string Name { get; set; }
	public string Email { get; set; }
	public string Password { get; set; }

	public User(string name,string email,string password)
	{
		Id = 1;
		Name =name;
		Email = email;
		Password = password;
	}

	public async Task ChangePassword(string pwd)
	{
		this.Password = pwd;
		await Task.CompletedTask;
	}
}

六、打印结果

image