Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind instance to inversify container

I'm using inversify with inversify-express-utils.

I have a quite usual inversify/express setup.

  • Controller
    • Service
      • A module
        • B module

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!

like image 770
matewilk Avatar asked Oct 17 '25 06:10

matewilk


1 Answers

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.

like image 68
matewilk Avatar answered Oct 18 '25 22:10

matewilk