I implement JwtService from IJwtService at the Infrastructure layer IJwtService declare at the Application layer and
I implement IdentityService from IIdentityService at the Infrastructure layer
I register both at infrastructure dependency injection like
services.AddTransient< IJwtService,JwtService>();
services.AddTransient<IIdentityService,IdentityService>();
Then I implement LoginQueryHandler implement from : IRequestHandler<LoginViewModel, LoginDto> within LoginQueryHandler() i inject IIdentityService and IJwtService
I register Mediator at Application Layer as this
services.AddMediatR(Assembly.GetExecutingAssembly());
using mediator I send a request to LoginQuery Handler
public async Task Login([FromBody] LoginViewModel model)
{
return await Mediator.Send(model);
}
This is 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;
}
}
}
but it throws the following error
System.InvalidOperationException: Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[Application.Login.Queries.LoginViewModel,Application.Login.Queries.LoginDto] Lifetime: Transient ImplementationType: Application.Login.Queries.LoginQueryHandler': Unable to resolve service for type 'TechneTravel.Infrastructure.Services.JwtService' while attempting to activate 'Newproject.Infrastructure.Identity.IdentityService'. ---> System.InvalidOperationException: Unable to resolve service for type 'Newproject.Infrastructure.Services.JwtService' while attempting to activate 'Newproject.Infrastructure.Identity.IdentityService'
Then I tried three ways to register Request Handler at the Application layer as bellow
services.AddTransient(typeof(IRequestHandler<LoginViewModel, LoginDto>), typeof(LoginQueryHandler));
services.AddTransient<IRequestHandler<LoginViewModel, LoginDto>, LoginQueryHandler>();
services.AddTransient(typeof(LoginQueryHandler));
but not solved
Based on your error message it seems that you are trying to resolve JwtService
in your Newproject.Infrastructure.Identity.IdentityService
but you have only interface registration:
services.AddTransient<IJwtService, JwtService>();
So either change your IdentityService
to accept IJwtService
instead of JwtService
(I would say that it is far better option) or change/add registration to inject using concrete class:
services.AddTransient<JwtService>();