Add Multiton Object Scope changes and PR documentation #584
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.
Add Multiton Object Scope to Swinject
Summary
This PR introduces a new object scope called
multiton
to Swinject. The multiton scope caches instances based on the arguments passed during resolution, allowing the same instance to be returned when resolving with identical arguments.Motivation
The multiton pattern is useful in scenarios where you want to:
Changes
Added
New Object Scope:
.multiton
MultitonStorage
class inSources/InstanceStorage.swift
Sources/ObjectScope.Standard.swift
Extended
InstanceStorage
Protocolfunc instance(inGraph:withArguments:) -> Any?
func setInstance(_:inGraph:withArguments:)
Container Resolution Enhancement
resolveWithArgumentCapture
method to extract and pass arguments to multiton storageDocumentation
Documentation/ObjectScopes.md
README.md
to include multiton in the feature listTests
Tests/SwinjectTests/ContainerTests.Multiton.swift
resetObjectScope
Modified
Container.swift
_resolve
method to detect multiton storage and use argument captureresolveAsWrapper
to support multiton scope for wrapped typesresolve
method to pass arguments to storage methodsInstanceStorage.swift
Usage
Important Notes
Hashable
: The multiton scope requires arguments to be hashable to use them as cache keysresetObjectScope(.multiton)
is calledImplementation Details
The multiton storage uses a dictionary to cache instances by their arguments. When arguments are provided during resolution:
For cases with no arguments, a special sentinel value is used as the cache key.
Testing
The implementation includes comprehensive tests covering:
Breaking Changes
None. The implementation maintains full backward compatibility through default protocol implementations.
Performance Impact
Minimal. The multiton scope adds a small overhead for:
This overhead is negligible compared to the potential savings from reusing instances.