InversifyJS icon indicating copy to clipboard operation
InversifyJS copied to clipboard

[feature] lazy singleton

Open xenoterracide opened this issue 3 years ago • 1 comments

I'd like a way to use a function to create a singleton. From what I understand from the documentation factories and providers return an instance, but said instance itself is not a singleton unless you do it in another way. Something like

container.bind('foo').creator(context => any).inSingletonScope()

would be super useful as sometimes there's stuff you want from the container in a function to create the object.

Obviously you can do some complex logic to do this in a factory, where you check if the value exists in the container, or bind it.

every DI system I've used can do this except, from what I can tell, this one.

xenoterracide avatar May 27 '22 18:05 xenoterracide

Hey @xenoterracide,

It was always possible with the .toDynamicValue() binding. The code should look something like that:

container.bind('foo').toDynamicValue(context => 'bar').inSingletonScope()

The foo service will be lazily initialized upon request.

dokmic avatar Aug 15 '22 13:08 dokmic