Feat: transient(...) function to complement the inject(...) function #56815
Labels
area: core
Issues related to the framework runtime
core: di
feature
Issue that requests a new feature
Milestone
Which @angular/* package(s) are relevant/related to the feature request?
No response
Description
With standalone components comes great responsibility - especially regarding service lifetimes.
The problem is that components will need some services, and it's a lot of guessing which ones have already been added to
providers
at a level above, which services should start anew (because they have state, which shouldn't be modified by sub-components by accident) and much more.My experience is that this leads to over-use
providers: [...]
because it's often a guesswork which providers are available from parent-level components and which ones are net. having everything it the ownproviders[...]
has a smell 💩 to it though.Basically sub-components could forget their own providers - and everything works - but this will result in them sharing the service by accident.
So it's fine if it's on purpose, but my experience is that it's accidental a lot, leading to difficult to debug issues.
Proposed solution
I propose a
transient(...)
method which is similar toinject(...)
, except that it ensures that the service it creates is only created once, and never reused.This would kind of result in shorter, nicer code
...than before (where you could never ensure that sub-components would reuse your service):
The code for the
transient(...)
which works looks like this - but I'm sure there's room for improvement:Alternatives considered
I guess we could also
transient
and therefor the injector would always create a new service - this would be a welcome addition anyhow, but my recommendation with thetransient(...)
injector would still be great, because you would not have to define theproviders
just to get a service.The text was updated successfully, but these errors were encountered: