Dependency Injection - Issue with Object containing AuthService instead of Instance of AuthService #4264
-
Hello, I'm starting to develop an API using AdonisJS. I've created a very first feature that allows creating a user. Initially, I developed this user creation using a classic and straightforward method: a route that calls a method from an AuthController, the controller calls an AuthService, the service calls the UserRepository responsible for creating the user. So far, no problems. Then, for more flexibility, I wanted to use dependency injection, and that's where things got tricky. Here in the attached images are the changes I made to implement dependency injection; there must be an error somewhere or something missing. When I run 'npm run dev', there's no issue, but as soon as I try to create a user with PostMan, I get the following error message: error:>> TypeError: this.authService.createUserAccount is not a function The console log at line 31 of AuthController indicates: So, we can see that 'AuthService' is an object containing a class, rather than an instance of the 'AuthService' class." Thank you for your help! Furthermore, I had a lot of difficulty setting up this code. I read various blog articles, asked ChatGPT, Bard, Claude, and searched for similar projects on Github. If there are errors in my code or if there's a simpler way to implement dependency injection in AdonisJS, I'd be very interested. Thanks again for your help! And keep up the great work with this framework; it looks fantastic! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I finally managed to find what was wrong in my code. There were 2 errors in the AppProvider.ts file: I needed to use AuthService, not the AuthService interface in the singleton. Here's the incorrect code: this.app.container.singleton('App/Services/ServicesContracts/AuthServiceContract', async () => {
const userRepository = this.app.container.use('App/DataAccessLayer/DALContracts/UserContract')
return new AuthService(userRepository)
}) Here's the corrected code (only the first line): this.app.container.singleton('App/Services/AuthService', () => {
const userRepository = this.app.container.use('App/DataAccessLayer/DALContracts/UserContract')
return new AuthService(userRepository)
}) |
Beta Was this translation helpful? Give feedback.
I finally managed to find what was wrong in my code. There were 2 errors in the AppProvider.ts file:
I needed to use AuthService, not the AuthService interface in the singleton.
And there was an unnecessary 'async'."
Here's the incorrect code:
Here's the corrected code (only the first line):