I'm using inversify
with inversify-express-utils
.
I have a quite usual inversify/express
setup.
B module
is a class that looks like this:
import { injectable } from 'inversify';
import SpellCorrector from 'spelling-corrector';
@injectable()
export class SpellCorrectorFactory {
private corrector: any;
constructor() {
this.corrector = new SpellCorrector();
this.corrector.loadDictionary();
}
public correct = (text: string): string => this.corrector.correct(text);
}
Now, the problem here is that as you can see in the constructor, I have this line of code:
this.corrector.loadDictionary()
This line takes over a second to execute.
So basically it seems like the actual instance creation is happening when I @inject
service B
to service A
So every time I make a request, the constructor of SpellCorrectorFactory
is being executed, so the request takes over 1000ms instead of below 100ms.
How can I bind this class to inversify so that during binding the class is being instantiated and in the A module
I have access to the instance which was created on app start, and not when I send a request to the express path?
Thanks in advance!
Ok, just in case someone looks at this page in search for an answer.
The solution is as simple as:
container
.bind<SpellCorrectorFactory>(TYPES.SpellCorrector)
.to(SpellCorrectorFactory)
.inSingletonScope();
This calls the constructor of the SpellCorrectorFactory
immediately and returns the instance.
So whenever you inject the result of this binding you have direct access to the instance and its functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With