Constructor inject not working
See original GitHub issueHei, i’m experiencing weird behaviour in my tests with constructor injects
//..
import {Container} from 'typedi';
import {AccessTokenService} from 'src/authentication/services/access-token-service';
import * as cfg from 'src/application/config';
Container.set('cfg.auth.jwt',cfg.auth.jwt);
const accessTokenService = Container.get(AccessTokenService);
accessTokenService.makeAccessToken(user);
//..
Dependecies are undefined when i configure them in the constructor
import {Service, Inject, Require} from 'typedi';
// ..
@Service('AccessTokenService')
export class AccessTokenService {
constructor(
@Require('moment') private moment,
@Require('jsonwebtoken') private jsonwebtoken,
@Inject('cfg.auth.jwt') private jwt
) {}
makeAccessToken(user: User) {
console.log(typeof this.jsonwebtoken); //undefined
console.log(typeof this.jwt); //undefined
console.log(typeof this.moment); //undefined
// ...
}
}
But this works
import {Service, Inject, Require} from 'typedi';
// ..
@Service('AccessTokenService')
export class AccessTokenService {
@Require('moment') private moment;
@Require('jsonwebtoken') private jsonwebtoken;
@Inject('cfg.auth.jwt') private jwt;
makeAccessToken(user: User) {
console.log(typeof this.jsonwebtoken); //object
console.log(typeof this.jwt); //object
console.log(typeof this.moment); //function
// ...
}
}
Issue Analytics
- State:
- Created 6 years ago
- Comments:13 (6 by maintainers)
Top Results From Across the Web
No results found
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found

Did you add import “reflect-metadata”; ?
When using classes, you don’t need to use
@Injectwhen injecting in the constructor. You simply write:I don’t know about using them with default exports for other modules, but why do you want to inject them at all? You can just start using them right away.