Skip to content

Instantly share code, notes, and snippets.

@yoichitgy
Created April 4, 2017 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoichitgy/31762ed1bbe7dbbb7000decbfe0d64c2 to your computer and use it in GitHub Desktop.
Save yoichitgy/31762ed1bbe7dbbb7000decbfe0d64c2 to your computer and use it in GitHub Desktop.
Swinject Example (Demo at iOSCon 2017 in London)
// 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 git@github.com: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