'Is it possible to inject a mix of runtime value and normal dependencies using tsyringe?
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.
Solution 1:[1]
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 instancehttps://github.com/microsoft/tsyringe#injecting-primitive-values-named-injection
https://github.com/microsoft/tsyringe/issues/193#issuecomment-1084181366
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Eric Xin Zhang |
