How to pass values in constructor using sigleton() in typescript?

2.3k Views Asked by At

I have a doubt about how to pass the value in the constructor using a singleton class in typescript.

mycode .ts

import {singleton} from "tsyringe";

@singleton()
class Foo {
  constructor(data:string) 
{
this.data = data
}
}

// some other file
import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";

const instance = container.resolve(Foo);

how to pass a value in the constructor using constainer .resolve function .any one gives the example code how to pass the value.

2

There are 2 best solutions below

1
Joachim On

You can do the following to inject a value into the constructor:

import {singleton} from "tsyringe";

@singleton()
class Foo {
  private str: string;
  constructor(@inject("SomeName") value: string) {
    this.str = value;
  }
}

// some other file
import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";

const str = "test";

container.register("SomeName", { useValue: str });
const instance = container.resolve(Foo);
0
Shadrech On

@user1762087 To answer your question, if you would like to supply different parameters to constructors for each instance you can do something like

import "reflect-metadata";
import {container} from "tsyringe";
import {Foo} from "./foo";

const str = "test";

container.registerInstance("SomeName", { useValue: str });
const instance = container.resolve(Foo);

// to clear up instances you've registered with registerInstance()
container.clearInstances();