typescriptadonis.jsadonisjs-ace

Cannot construct [class LoginController] class with AdonisJs v6


I have some problem with class AdonisJS.

My code LoginController

export default class LoginController {
  constructor(protected authService: AuthService) {}

  @inject()
  doLogin({ request }) {
    return this.authService.doLogin(request)
  }
}

Code AuthService

export default class AuthService {
  constructor(private userRepository: UserRepositoryInterface) {}

  // login user
  @inject()
  async doLogin(request: any) {
    const { email, password } = request.only(['email', 'password'])

    try {
      // get user by email
      const user = await this.userRepository.getByEmail(email)

      if (!user) {
        
      } else {
        if (user.active === StatusEnum.ACTIVE) {
          const userLogin = this.userRepository.verifyCredentials(email, password)
          if (await userLogin) {
            const token = this.userRepository.createToken(user)

            const response = {
              token: token,
            }

           
          } else {
            
          }
        } else {
          
        }
      }
    } catch (error) {
      
    }
  }
}

I call AuthService in LoginController as that, and thats work

private authService = new AuthService

The goal is call in constructor for using in all function code, and the error is below

In execution I receive this error

"message": "Cannot construct \"[class LoginController]\" class. Container is not able to resolve its dependencies. Did you mean to use @inject decorator",
"name": "RuntimeException",
"status": 500,

Can you help?

Thank you


Solution

  • You get this error because of the position of the @inject() decorator.

    You have to use the @inject() decorator on top of where you want to inject.

    For example, you must write the decorator above the class declaration to inject something inside your class's constructor.

    @inject()
    class MyService {
      constructor(private someOtherService: SomeOtherService) {}
    }
    

    This code will inject an instance of SomeOtherService in your constructor.

    If you want to inject something directly into a method, you must write the decorator above the method declaration.

    class AuthController {
      @inject()
      doLogin({}: HttpContext, someOtherService: SomeOtherService) {}
    }
    

    Here, we inject an instance of SomeOtherService directly inside the method.

    --

    Therefore, to correct your issue, you must write the @inject() decorator above your class declaration since you want to inject your dependency inside your class's constructor.