You need to enable JavaScript to run this app. 启用GetAllBooks查询处理器时遇MediatR依赖注入错误
优惠活动
大模型
产品
解决方案
定价
更多

启用GetAllBooks查询处理器时遇MediatR依赖注入错误

CQRS架构下GetAllBookQueryHandler依赖注入失败问题排查与解决

问题现象

启用GetAllBooks文件夹内的处理器时,触发以下依赖注入错误:

Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler2[BookAPI.Application.Features.Queries.Book.GetAllBooks.GetAllBookQueryRequest,System.Collections.Generic.List1[BookAPI.Application.Features.Queries.Book.GetAllBooks.GetAllBookQueryResponse]] Lifetime: Transient ImplementationType: BookAPI.Application.Features.Queries.Book.GetAllBooks.GetAllBookQueryHandler': Unable to resolve service for type 'BookAPI.Application.Repositories.IBookReadRepository' while attempting to activate 'BookAPI.Application.Features.Queries.Book.GetAllBooks.GetAllBookQueryHandler'.)

其他如客户列表、创建类的处理器均能正常工作,仅GetAllBookQueryHandler出现此问题。

相关代码片段

GetAllBookQueryHandler

public class GetAllBookQueryHandler : IRequestHandler<GetAllBookQueryRequest, List<GetAllBookQueryResponse>>    
{        
    private IBookReadRepository bookReadRepository;        
    public GetAllBookQueryHandler(IBookReadRepository bookReadRepository)        
    {            
        this.bookReadRepository = bookReadRepository;        
    }        
    public async Task<List<GetAllBookQueryResponse>> Handle(GetAllBookQueryRequest request, CancellationToken cancellationToken)        
    {            
        List<B.Book> books = bookReadRepository.GetAll().Include(x=>x.Authors).Include(x=>x.Category).Include(x=>x.BookImages).ToList();            
        List<GetAllBookQueryResponse> responses = new();            
        foreach (B.Book book in books)             
        {                
            responses.Add(                    
                new GetAllBookQueryResponse                     
                {                        
                    Name= book.Name,                        
                    CategoryName=book.Category.Name,                        
                    AuthorName=book.Authors.First().Name,                        
                    Img=book.BookImages.First().Path,                        
                    UnitPrice=book.UnitPrice,                    
                    }                    
                );            
        }            
        return responses;        
    }    
}

GetAllBookQueryRequest

public class GetAllBookQueryRequest : IRequest<List<GetAllBookQueryResponse>>    
{        
    // 空类,用于请求所有书籍
}

GetAllBookQueryResponse

public class GetAllBookQueryResponse    
{        
    public int Id { get; set; }        
    public string Name { get; set; }        
    public string CategoryName { get; set; }        
    public string AuthorName { get; set; }        
    public string Img { get; set; }        
    public ushort UnitPrice { get; set; }    
}

应用层服务注册(IoC)

using MediatR;
using Microsoft.Extensions.DependencyInjection;

namespace BookAPI.Application
{    
    public static class ServiceRegistration    
    {        
        public static void AddApplicationServices(this IServiceCollection services)        
        {            
            // 扫描所有请求、处理器并注入IoC
            services.AddMediatR(typeof(ServiceRegistration));            
            services.AddHttpClient();        
        }    
    }
}

Program.cs中服务引入

builder.Services.AddApplicationServices();

Book控制器

// ...
readonly IMediator mediator;        
public BookController(IBookWriteRepository bookWriteRepository, IWebHostEnvironment webHostEnvironment, IFileService fileService, IMediator mediator)        
{            
    bookWriteRepository = bookWriteRepository;            
    _fileService = fileService;            
    this.mediator = mediator;        
}        
[HttpGet]        
public async Task<IActionResult> GetAllBooks([FromQuery] GetAllBookQueryRequest getAllBookQueryRequest)        
{            
    return Ok(await mediator.Send(getAllBookQueryRequest));        
}
// ...

问题原因

错误核心是**IBookReadRepository未被注册到依赖注入容器中**。其他处理器正常工作的原因是它们依赖的是已注册的仓储(比如控制器中用到的IBookWriteRepository),而IBookReadRepository的注册逻辑被遗漏了。

解决办法

  1. 补充仓储注册:找到仓储层的服务注册类(通常在Infrastructure项目中),添加IBookReadRepository的注册逻辑,示例:
// 假设BookReadRepository是IBookReadRepository的实现类
services.AddScoped<IBookReadRepository, BookReadRepository>();

// 如果使用通用仓储模式,确保ReadRepository被正确扫描注册,比如:
services.AddScoped(typeof(IReadRepository<>), typeof(ReadRepository<>));
  1. 确认仓储层服务已引入:在Program.cs中确保已添加仓储层的服务注册,比如:
builder.Services.AddInfrastructureServices(); // 替换为实际的仓储层注册方法名
  1. 检查命名空间:验证GetAllBookQueryHandler中引用的IBookReadRepository命名空间是否正确,避免因命名空间错误导致容器无法识别服务。

内容的提问来源于stack exchange,提问作者Mustafa Sahin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:41:47