.Net MediatR 的使用(事件、管道(AOP)、命令)

Nuget包

  • 这里我创建的是命令行项目,因此还要额外添加一个DI包

命令

测试命令

  • 继承 IRequest
  • 如果是返回值得命令,去掉泛型即可,IRequest --> IRequest
  • IRequestHandler<TestCommand,string> --> IRequestHandler

using MediatR;

namespace AOP.Mediator.Commands;

public record TestCommand(string Name) : IRequest<string>
{
}

命令处理者

  • 基础 IRequestHandler
using MediatR;

namespace AOP.Mediator.Commands;

public class TestCommandHandler:IRequestHandler<TestCommand,string>
{
    public Task<string> Handle(TestCommand request, CancellationToken cancellationToken) {
        Console.WriteLine(request.Name);
        return  Task.FromResult("ans");
    }
}

发送命令

  • 从容器中获取 IMediator
IMediator mediator = container.GetRequiredService<IMediator>();
var result = mediator.Send(new TestCommand("我是命令"));

效果

其他别管,主看红框的打印。

事件

  • 注意,事件是没有返回值得。

事件

  • 继承 INotification
using MediatR;

namespace AOP.Mediator.Events;

public record TestEvent(string Name) : INotification
{
}

事件处理者

  • 继承 INotificationHandler
using MediatR;

namespace AOP.Mediator.Events;

public class TestEventHandler:INotificationHandler<TestEvent>
{
    public async Task Handle(TestEvent notification, CancellationToken cancellationToken) {
        Console.WriteLine($"Event:{notification.Name}");
    }
}

发布事件

var container = serviceCollection.BuildServiceProvider();
IMediator mediator = container.GetRequiredService<IMediator>();

mediator.Publish(new TestEvent("我是事件"));

效果

管道(AOP)

管道切面

  • 继承 IPipelineBehavior<IRequest, IResponse>
using System.Linq.Expressions;
using MediatR;

namespace AOP.Mediator.Pipes;

public class TransactionPipeBehavior<IRequest, IResponse> : IPipelineBehavior<IRequest, IResponse> where TRequest : notnull
{
    public async Task<IResponse> Handle(IRequest request, RequestHandlerDelegate<IResponse> next,
        CancellationToken cancellationToken) {
        Console.WriteLine("开始事务");
        var response = await next();
        Console.WriteLine("结束事务");
        return response;
    }
}



public class ExpressionPipeBehavior<TRequest,TResponse>:IPipelineBehavior<TRequest,TResponse> where TRequest : notnull
{
    public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken) {

        try {
            var result= await next();
            return result;
        }
        catch (Exception e) {
            Console.WriteLine($"异常捕获:{nameof(e)}");
            throw;
        }
    }
}

注册切面

  • 推荐 将其注册为Scoped
  • 最先注册的范围越大

    //添加管道切面
    config.AddBehavior(typeof(IPipelineBehavior<,>), typeof(TransactionPipeBehavior<,>),
        serviceLifetime: ServiceLifetime.Scoped);
    config.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ExpressionPipeBehavior<,>),
        serviceLifetime: ServiceLifetime.Scoped);

效果

posted @ 2023-12-15 23:45    阅读(374)  评论(0)    收藏  举报