MediatR:INotification 处理程序被多次调用

MediatR: INotification handler is being called multiple times

我正在使用 MediatR 9.0.0(MediatR.Extensions.Microsoft.DependencyInjection 9.0.0)。我有这样的事件通知处理程序:

public class StatusChangedEventHandler : INotificationHandler<StatusChangedEvent>
{
    
   public StatusChangedEventHandler ()
   {
   }
    
   public async Task Handle(StatusChangedEvent evnt, CancellationToken cancellationToken)
   {
      //some code 
   }
}

正在从另一个命令处理程序发布事件:

public class ChangeStatusCommandHandler : IRequestHandler<ChangeStatusCommand, bool>
    {
        ...
        private readonly IMediator _mediator;

        public ChangeStatusCommandHandler(...,IMediator mediator)
        {
            ...
            _mediator = mediator;
        }

        public async Task<bool> Handle(ChangeStatusCommand command, CancellationToken cancellationToken)
        {

            ...

            await _mediator.Publish(new StatusChangedEvent(int id, string message));

            ...
            
        }
    }

问题是 StatusChangedEventHandler.Handle 方法被多次调用 - 我注意到它似乎与 Startup.cs 中注册的命令处理程序的数量有关,例如

services.AddMediatR(typeof(CommandA));

=> 处理程序将被调用一次

services.AddMediatR(typeof(CommandA));
services.AddMediatR(typeof(CommandB));

=> 处理程序将被调用两次

services.AddMediatR(typeof(CommandA));
services.AddMediatR(typeof(CommandB));
services.AddMediatR(typeof(CommandC));

=> 处理程序将被调用 3 次等

如何解决这个问题,使处理程序只被调用一次?

services.AddMediatR(typeof(CommandA)) 的调用不仅注册了单个命令处理程序 CommandA,它还注册了包含 CommandA 的程序集中存在的所有命令处理程序;正在扫描整个程序集以查找其处理程序。

来自documentation

Scans assemblies and adds handlers, preprocessors, and postprocessors implementations to the container. To use, with an IServiceCollection instance:

您不得在其他命令处理程序上显式调用 AdMediatR; 删除下面的。

services.AddMediatR(typeof(CommandB));
services.AddMediatR(typeof(CommandC));