【问题标题】:What is the execution order of Multiple Pipeline Behaviors in MediatRMediatR中多个管道行为的执行顺序是什么
【发布时间】:2022-08-02 18:44:08
【问题描述】:

假设我在.NET6ConfigureServices 类中的MediatR 中有这些行为:

        services.AddMediatR(Assembly.GetExecutingAssembly());
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(AuthorizationBehaviour<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));

并且此行为应该在实现IRequestHandler 的所有具体CommandHandler 之前执行。

那么这些行为的执行顺序是怎样的呢?如何设置行为执行的优先级?

    标签: c# .net-6.0 mediatr


    【解决方案1】:

    作为 mediatR 东西的初学者,我知道这些行为的执行顺序来自于在 ConfigureServices 中注册这些服务的顺序,或者您在应用程序中调用的任何内容。 对于您的情况,这些行为的执行顺序将是 例外>>授权>>验证>>性能。

    但是如果更改 configureservices 中的注册顺序,即在第二位注册 UnhandledException Behavior 并在第一位注册 Authorization。

     services.AddTransient(typeof(IPipelineBehavior<,>), typeof(AuthorizationBehaviour<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehaviour<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehaviour<,>));
        services.AddTransient(typeof(IPipelineBehavior<,>), typeof(PerformanceBehaviour<,>));
    

    然后执行顺序如下 授权>>异常>>验证>>性能。 有 IRequestPreProcessor,PostProcessor 在请求执行之前/之后执行的 MediatR 中也非常有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多