Is it possible to inject a mix of runtime value and normal dependencies using tsyringe?

818 Views Asked by At

I'm using @launchtray/tsyringe (a fork of Microsoft tsyringe with async initialization support) which is quite handy.

I'd like to implement something like the following:

A orchestration service whose constructor accepts dependency services (can be injected using @inject decorator) and a runtime value:

@injectable()
class OrchestrationService {
  constructor(
    @inject(ServiceA) private dependencyA: ServiceA,
    @inject(ServiceA) private dependencyB: ServiceB,
    runtimeValue: string,
  ) {
    this.init(runtimeValue);
  }
}

And then I can somehow resolve the instance using a runtime value:

const orchestrationService = container.resolve<OrchestrationService>(runtimeValue);

I don't know all possible runtime values therefore cannot register them beforehand.

I am wondering if injecting runtime value is possible and how to achieve that.

1

There are 1 best solutions below

0
On

I posted the same question in tsyringe github repo and Andrey Khapugin answered my question. It's not perfect but I reckon it's the best we can get.

you can register value in container

const SomeToken:InjectionToken<string> = "MyToken";

class Service{
  constructor(
    @inject(ServiceA) private dependencyA: ServiceA,
    @inject(ServiceA) private dependencyB: ServiceB,
    @inject(SomeToken) runtimeValue: string,
  )
}

container.registerInstance(SomeToken, "runtimeValue");
container.resolve(SomeToken); // runtimeValue
container.resolve(Service); // Service instance

https://github.com/microsoft/tsyringe#injecting-primitive-values-named-injection

https://github.com/microsoft/tsyringe/issues/193#issuecomment-1084181366