Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Shared<Instance> type to annotate provider method of shared instance #32

Merged
merged 8 commits into from Dec 30, 2017

Conversation

@ishkawa
Copy link
Owner

commented Dec 29, 2017

#30

When return type of provider method is wrapped in Shared<Instance> type, resolver always returns the same instance. The life-cycle of shared instance is associated with the instance of Resolver.

For example, suppose a conformer of Resolver is declared as below:

protocol AppResolver: DIKit.Resolver {
    func provideCounter() -> Shared<Counter>
}

final class AppResolverImpl: AppResolver {
    var sharedInstances = [:] as [String : Any]
    
    func provideCounter() -> Shared<Counter> {
        let counter = Counter(dependency: .init(value: 0))
        return Shared(counter)
    }
}

Then, dikitgen generates following protocol extension:

extension AppResolver {

    func resolveCounter() -> Counter {
        if let sharedInstance = sharedInstances["Counter"] as? Counter {
            return sharedInstance
        }
        let sharedInstance = provideCounter().instance
        sharedInstances["Counter"] = sharedInstance
        return sharedInstance
    }

}

A property sharedInstances is added to Resolver protocol to retain shared instances, and conformers of Resolver protocol are constrained to class only.

public protocol Resolver: class {
    var sharedInstances: [String: Any] { get set }
}

Conformers are expected to have the property as a stored property like below:

final class AppResolverImpl: AppResolver {
    var sharedInstances = [:] as [String : Any]
    
    ...
}

@ishkawa ishkawa changed the title Add Shared<Instance> type to annotate scope of provider method Add Shared<Instance> type to annotate provider method of shared instance Dec 29, 2017

@ishkawa ishkawa merged commit 3f9e72f into develop Dec 30, 2017

2 checks passed

continuous-integration/travis-ci/pr The Travis CI build passed
Details
continuous-integration/travis-ci/push The Travis CI build passed
Details

@ishkawa ishkawa deleted the shared-instance branch Dec 30, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
1 participant
You can’t perform that action at this time.