wessberg/DI

Injecting a constant or dynamic value

jamarzka opened this issue · 2 comments

Do you have any plans to add support for injecting constant or dynamic values at runtime?

https://github.com/inversify/InversifyJS/blob/master/wiki/value_injection.md

You can inject singletons and transients.

Singletons always will inject the same instance (e.g. "constant values") whereas transients will always instantiate a new service (e.g. "dynamic values") or re-evaluate the given callback and return some value and use that as the service. If I understand your question correctly, I think the following piece of code would suit your use case:

const container = new DIContainer();
container.registerTransient<IMyInterface>(() => something);

It is dynamic in the sense that the callback is evaluated for each injection, and you are free to return whatever value you like in the callback, as long as it implements the interface.

That works! Thanks