Mediatr 是如何连线的?

How is Mediatr wired?

更新:

项目中的 Mediatr 没有使用任何自定义逻辑来发送消息。我可以说它用作事件聚合器吗?


https://github.com/JasonGT/NorthwindTraders的源代码中,Controller从ControllerBase获取Mediator。

[ApiController]
[Route("api/[controller]/[action]")]
public abstract class BaseController : ControllerBase
{
    private IMediator _mediator;

    protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
}

在控制器中,它调用Mediator.Send(...)向中介发送消息。

public class EmployeesController : BaseController
{
    // ....
    [HttpGet("{id}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public async Task<ActionResult<EmployeeDetailVm>> Get(int id)
    {
        return Ok(await Mediator.Send(new GetEmployeeDetailQuery { Id = id }));
    }

而查询消息GetEmployeeDetailQuery会调用内部classGetEmployeeDetailQuery.GetEmployeeDetailQueryHandler中的方法Handle()。这是怎么接线的?

public class GetEmployeeDetailQuery : IRequest<EmployeeDetailVm>
{
    public int Id { get; set; }

    public class GetEmployeeDetailQueryHandler : IRequestHandler<GetEmployeeDetailQuery, EmployeeDetailVm>
    {
        private readonly INorthwindDbContext _context;
        private readonly IMapper _mapper;

        public GetEmployeeDetailQueryHandler(INorthwindDbContext context, IMapper mapper)
        {
            _context = context;
            _mapper = mapper;
        }

        public async Task<EmployeeDetailVm> Handle(GetEmployeeDetailQuery request, CancellationToken cancellationToken)
        {
            var vm = await _context.Employees
                .Where(e => e.EmployeeId == request.Id)
                .ProjectTo<EmployeeDetailVm>(_mapper.ConfigurationProvider)
                .SingleOrDefaultAsync(cancellationToken);

            return vm;
        }
    }
}

在该项目的 startup.cs 中,有一个对 AddApplication 的调用,它是 NorthwindTraders.Application 项目的扩展方法,并在 DependencyInjection.cs 中定义。这会调用 services.AddMediatR(Assembly.GetExecutingAssembly());,它会扫描程序集以查找处理程序并注册它们。

一般来说,您可以通过在 Web 应用程序的 Startup.ConfigureServices 方法中调用 services.AddMediatr(Assembly.GetExecutingAssembly()) 来为您自己的项目注册 MediatR。