I'm working on a backend solution in Node.js and Express, using Typescript. I'm trying to do dependency injection similar to Angular, but lacking the @Injectable()
decorator I'm doing this:
Dependency:
export class SomeDependency {
public someMethod() {
console.log('Some method is running');
}
}
Parent:
import { SomeDependency } from './someDependency';
export class Whatever {
constructor(
private someDependency = new SomeDependency()
) {}
public doSomething() {
console.log('Look, I\'m doing something!');
this.someDependency.someMethod();
}
}
It works, but it may not be the best way. Any suggestions on how to improve it are appreciated.
On the other hand, what do you guys think: is it better to import dependencies like this, in the constructor, or create new
instance every time, or most of the time? Like this:
import { SomeDependency } from './someDependency';
export class Whatever {
public doSomething() {
console.log('Look, I\'m doing something!');
new someDependency().someMethod();
}
}
As SomeDependency
isn't a singleton, I wonder which one is less efficient: keeping an instance alive in the parent, or creating a new one every time, letting the garbage collector take care of it when the call finished.