我在基础设施层从IJwtService实现JwtService IJwtService 在应用层声明 和
我在基础设施层从IIdentityService实现IdentityService
我都在基础设施依赖注入(inject)上注册,就像
services.AddTransient< IJwtService,JwtService>();
services.AddTransient<IIdentityService,IdentityService>();
然后我实现 LoginQueryHandler 实现: IRequestHandler
我在应用层注册Mediator是这样的
services.AddMediatR(Assembly.GetExecutingAssembly());
使用中介器向 LoginQuery Handler 发送请求
public async Task Login([FromBody] LoginViewModel model)
{
return await Mediator.Send(model);
}
这是 LoginQueryHandler 类
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]时出错”生命周期: transient 实现类型:Application.Login.Queries.LoginQueryHandler ':尝试激活“Newproject.Infrastruct.Identity.IdentityService”时无法解析类型“TechneTravel.Infrastruct.Services.JwtService”的服务。 ---> System.InvalidOperationException:尝试激活“Newproject.Infrastruct.Identity.IdentityService”时无法解析类型“Newproject.Infrastruct.Services.JwtService”的服务
然后我尝试了三种方法在应用程序层注册Request Handler,如下所示
services.AddTransient(typeof(IRequestHandler<LoginViewModel, LoginDto>), typeof(LoginQueryHandler));
services.AddTransient<IRequestHandler<LoginViewModel, LoginDto>, LoginQueryHandler>();
services.AddTransient(typeof(LoginQueryHandler));
但没有解决
最佳答案
根据您的错误消息,您似乎正在尝试解析 Newproject.Infrastruct.Identity.IdentityService
中的 JwtService
,但您只有接口(interface)注册:
services.AddTransient<IJwtService, JwtService>();
因此,要么更改您的 IdentityService
以接受 IJwtService
而不是 JwtService
(我想说这是更好的选择),或者更改/添加使用具体类注册注入(inject):
services.AddTransient<JwtService>();
关于cqrs - 验证服务描述符“ServiceType : MediatR. IRequestHandler”时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70528225/