验证服务描述符 'ServiceType: MediatR.IRequestHandler 时出错

Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler

我在基础设施层IJwtService实现JwtService IJwtService应用层声明

我在 Infrastructure

IIdentityService 实现 IdentityService

我在 基础设施依赖注入 上都注册了

services.AddTransient< IJwtService,JwtService>();
services.AddTransient<IIdentityService,IdentityService>();

然后我实现 LoginQueryHandler 实现:IRequestHandler 在 LoginQueryHandler() 我注入 IIdentityService 和 IJwtService

我在应用层注册Mediator是这样的

services.AddMediatR(Assembly.GetExecutingAssembly());

我使用调解器向登录查询处理程序发送请求

public async Task Login([FromBody] LoginViewModel model)
{

        return await Mediator.Send(model);
}

这是 LoginQueryHandler Class

public class LoginViewModel: IRequest<LoginDto>
{
public string Email { get; set; }
public string Password { get; set; }


}
public class LoginQueryHandler : IRequestHandler<LoginViewModel, LoginDto>
{

private readonly IIdentityService _identityService;
private readonly IJwtService _jwtService;
public LoginQueryHandler(IIdentityService identityService,IJwtService jwtService)
{
    _identityService=identityService;
    _jwtService=jwtService;
    
}

public async Task<LoginDto> Handle(LoginViewModel request, CancellationToken cancellationToken)
{
    try
    {
        var user = await _identityService.FindByEmailAsync(request.Email);
       // codes....
        return new LoginDto();
    }
    catch (Exception ex)
    {
        throw ex;
    }
   
}
}

但它抛出以下错误

System.InvalidOperationException:验证服务描述符 'ServiceType: MediatR.IRequestHandler`2[Application.Login.Queries.LoginViewModel,Application.Login.Queries.LoginDto] Lifetime: Transient ImplementationType: Application.Login.Queries.LoginQueryHandler' 时出错:尝试激活 'Newproject.Infrastructure.Identity.IdentityService' 时无法解析类型 'TechneTravel.Infrastructure.Services.JwtService' 的服务。 ---> System.InvalidOperationException:尝试激活 'Newproject.Infrastructure.Identity.IdentityService'

时无法解析类型 'Newproject.Infrastructure.Services.JwtService' 的服务

然后我尝试了三种方式在Application层注册Request Handler如下

services.AddTransient(typeof(IRequestHandler<LoginViewModel, LoginDto>), typeof(LoginQueryHandler));

 services.AddTransient<IRequestHandler<LoginViewModel, LoginDto>, LoginQueryHandler>();
 services.AddTransient(typeof(LoginQueryHandler));

还没解决

根据您的错误消息,您似乎正在尝试解决 Newproject.Infrastructure.Identity.IdentityService 中的 JwtService 但您只有接口注册:

services.AddTransient<IJwtService, JwtService>();

所以要么改变你的 IdentityService 以接受 IJwtService 而不是 JwtService (我会说这是更好的选择)或 change/add 注册以使用混凝土注入class:

services.AddTransient<JwtService>();