version 2.4 "Damiya" of their web framework... By embracing dependency injection, the refactoring towards better modularization that was started in 2.3 has continued in this release... Play has already supported dependency injection in earlier versions, but now it comes out of the box and its use is even encouraged. "Play 2.4 Moves to Dependency Injection and Java 8"
let name: String init(name: String) { self.name = name } func sound() -> String { return "Meow!" } } class PetOwner { let pet = Cat(name: "Mimi") func play() -> String { return "I'm playing with \(pet.name). \(pet.sound())" } } let petOwner = PetOwner() print(petOwner.play()) // prints "I'm playing with Mimi. Meow!" Hardcoded Assume we are developing a pet game...
String) { self.name = name } func sound() -> String { return "Bow wow!" } } let dogOwner = PetOwner(pet: Dog(name: "Hachi")) print(dogOwner.play()) // prints "I'm playing with Hachi. Bow wow!" (or loosely coupled components) PetOwner can have a dog!
a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. Wikipedia: Dependency injection
container.register(AnimalType.self) { _ in Cat(name: "Mimi") } container.register(PetOwner.self) { r in PetOwner(pet: r.resolve(AnimalType.self)!) } https://github.com/Swinject/Swinject Swinject let petOwner = container.resolve(PetOwner.self)! print(petOwner.play()) // prints "I'm playing with Mimi. Meow!" Registration: Resolution: Cat is instantiated automatically when PetOwner is instantiated!
components. • DI Container stores dependency graph and provides instances upon requests. • Software architecture with Dependency Injection is easier to test, maintain and organize.