0

I am new to Typescript and InversifyJS. What I am trying to achieve is to share variable value across multiple files. I am setting the value on the server startup on main.ts and I am trying to fetch that value from a controller. What I did is I created a @injectable service file

service.ts

 import { injectable } from 'inversify';

    @injectable()
    export class SetGetService  {

        private _client : any;

        get () : any {
            return this._client;
        }

        set (client: any) {
            this._client = client;
        }                                                                           
  } 

I am able to set the value from main.ts, but after calling the SetGetService on other files, it was undefined or empty. It seems like it was being reset or cleared.

Jed Nocum
  • 80
  • 11

1 Answers1

3

You can do the following in the main.ts file:

const client = new Client();
container.bind<Client>("Client").toConstantValue(client);

Then in the service:

import { injectable, inject } from 'inversify';

@injectable()
export class SetGetService  {

    @inject("Client") private _client: Client;

    get () : any {
        return this._client;
    }

    set (client: any) {
        this._client = client;
    }                                                                           
} 

If the client is a DB client and its initialization is async you might want to use the following:

// ioc_modules.ts

const asyncModule = new AsyncContainerModule(async (bind) => {
    const client = await Client.getConnection();
    bind<Client>("Client").toConstantValue(client);
});

// main.ts

(async () => {
    await container.loadAsync(asyncModule);
})()
Remo H. Jansen
  • 23,172
  • 11
  • 70
  • 93
  • Hi! thank you for the answer, what does the "Client" contains? – Jed Nocum Mar 22 '18 at 03:30
  • "Client" is just a string used as ID, in TypeScript IDs cannot be interfaces because interfaces are removed from the code during the compilation, so they are not available at runtime. You can use a string a class or a symbol as ID. – Remo H. Jansen Mar 22 '18 at 09:31
  • Hi sorry for the delay. It says cannot find name "Client"? – Jed Nocum Mar 26 '18 at 11:11
  • This is sad state of things. Because as soon as you call `loadAsync` it will create a DB connection. Which misses the point of lazy initialization of a DI system. With the same result one can write `bind("Client").toConstantValue(await Client.getConnection());` and avoid `AsyncContainerModule` abstraction altogether – Nick Olszanski Feb 13 '22 at 20:48