Introduce Weak Singleton. Provide dependencies based on arguments #451
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Introduction of Weak Singleton
Needle has been providing users with singleton dependencies through its shared method, which is the most common use case for dependency injection. However, there are situations where weak singletons can be more appropriate.
For instance, when multiple objects require the same new dependency, using a weak singleton instead of a traditional singleton can be more efficient. In such a case dependency provided as a weak singleton can be safely destroyed when no one needs it and recreated again when it's used, as opposed to singleton which remains in memory and potentially retaining previous state.
Introduction of arguments
There are cases, when it's convenient to create unique object per some unique feature. For example, you might need a separate object per object id or you might want to make unique data fetcher per endpoint, etc
With this change, it would be possible to create an object based on arguments. Arguments is an instance which should be
Hashable
for comparison. Providing different arguments for singleton will result in a new singleton per unique argument. The same logic applies to weak singletons.Example:
Replace
String
withStaticString
in#function
In the current needle implementation
__function
parameter used as a key for dependency which is great because it's unique in the scope of the component and it's efficient.Since arguments is introduced and
__function
is not the only key to dependency anymore, we can consider usingStaticString
instead.#function
expression is replaced with the actual value at a compile time, so they are basicallyStaticString
. As an adventage,StaticString
can be compared by reference which is faster than string comparisonIt's not a required change but seems to be appropriate in the context of arguments introduction
Side notes
weakSingleton
&args
inComponent
but not forAssemblyStorage
. It seems thatComponent
tests should be enough to coverAssemblyStorage
usage