Last active
January 20, 2020 08:17
-
-
Save Wancieho/9d07d07843deb5959c7ef807aa70e4b5 to your computer and use it in GitHub Desktop.
TypeScript DI (InversifyJS) dynamic instance issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { injectable } from 'inversify'; | |
import Enemy from './enemy'; | |
import Engine from './engine'; | |
@injectable() | |
export default class Creator { | |
constructor( | |
@inject(Engine) private engine: Engine, | |
) { | |
this.engine.init(); | |
// How do I create instances of an enemy as Enemy has the Helpers dependency that needs to be injected | |
// If I were to inject Enemy as a dependency in this constructor I'm not able to create instances | |
// Do I somehow use a Factory class? | |
const enemy1: Enemy = new Enemy(); | |
const enemy2: Enemy = new Enemy(); | |
const enemy3: Enemy = new Enemy(); | |
enemy1.create('Joe'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { injectable } from 'inversify'; | |
import Helpers from './helpers'; | |
@injectable() | |
export default class Enemy { | |
private name: string; | |
constructor( | |
@inject(Helpers) private helpers: Helpers, | |
) { } | |
public create(name: string): void { | |
this.name = name; | |
this.helpers.doSomething(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { injectable } from 'inversify'; | |
@injectable() | |
export default class Helpers { | |
public doSomething(): void { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment