Created
April 4, 2017 02:54
-
-
Save yoichitgy/31762ed1bbe7dbbb7000decbfe0d64c2 to your computer and use it in GitHub Desktop.
Swinject Example (Demo at iOSCon 2017 in London)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Demo at iOSCon 2017 in London | |
// https://speakerdeck.com/yoichitgy/dependency-injection-in-practice-ioscon | |
// | |
// Tested with: Xcode 8.2.1 | |
// | |
// How to Use: | |
// 1. Clone Swinject: git clone --recursive [email protected]:Swinject/Swinject.git | |
// 2. Checkout 2.0.0 branch: cd Swinject; git checkout 2.0.0 | |
// 3. Build the Swinject project for a simulator target | |
// 4. Open the playground in the project | |
// 5. Replace the code of the playground with the following code | |
// 6. Run the playground | |
import Swinject // https://github.com/Swinject/Swinject | |
protocol Animal: class { } | |
class Cat: Animal { } | |
class PetOwner { | |
let pet: Animal | |
init(pet: Animal) { | |
self.pet = pet | |
} | |
} | |
// At program entry point | |
let container = Container() | |
container.register(PetOwner.self) { (resolver) in | |
PetOwner(pet: resolver.resolve(Animal.self)!) | |
} | |
container.register(Animal.self) { _ in | |
Cat() | |
}.inObjectScope(.container) | |
// Anywhere later | |
let anya = container.resolve(PetOwner.self)! | |
let yoichi = container.resolve(PetOwner.self)! | |
anya !== yoichi | |
anya.pet === yoichi.pet |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment