CocoaPods trunk is moving to be read-only. Read more on the blog, there are 19 months to go.

DGDependencyInjector 2.0.1

DGDependencyInjector 2.0.1

TestsTested
LangLanguage SwiftSwift
License BSD
ReleasedLast Release Jul 2017
SwiftSwift Version 3.0
SPMSupports SPM

Maintained by Benoit BRIATTE.



  • By
  • Digipolitan

DGDependencyInjector

Dependency injector Swift. Compatible for swift server-side and swift for iOS

The Basics

First you must create a Module and register some providers

let module = Module()
module.bind(IAnimal.self).to(Dog.self)

IAnimal is a protocol that MUST be implemented by the Dog class

public protocol IAnimal {

    var name: String { get }

    func scream() -> String
}

open class Dog: IAnimal, Injectable {

    public var name: String

    public required convenience init(injector: Injector, arguments: [String : Any]?) throws {
        self.init(name: arguments?["name"] as? String ?? "Athina")
    }

    init(name: String) {
        self.name = name
    }

    public func scream() -> String {
        return "Barking"
    }
}

After that, you must register your module inside an injector

Injector.default.register(module: module)

Finally, inject an IAnimal and retrieve a concrete class registered inside your module

if let animal = try? Injector.default.inject(IAnimal.self) {
  print(animal.name) // print Athina
  print(animal.scream()) // print Barking
}

Advanced

Arguments

Register a provider that handle arguments :

let module = Module()
module.bind(IAnimal.self).with { (_, arguments) -> IAnimal? in
  if let name = arguments?["name"] as? String {
    return Dog(name: name)
  }
  return nil
}
Injector.default.register(module: module)

Inject an IAnimal with arguments Dictionary<String, Any> :

if let animal = Injector.default.inject(IAnimal.self, arguments: ["name": "Athina"]) {
  print(animal.name) // print Athina
  print(animal.scream()) // print Barking
}
if let otherAnimal = Injector.default.inject(IAnimal.self, arguments: ["name": "Yoda"]) {
  print(otherAnimal.name) // print Yoda
  print(otherAnimal.scream()) // print Barking
}

Contributing

See CONTRIBUTING.md for more details!

This project adheres to the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to [email protected].

License

DGDependencyInjector is licensed under the BSD 3-Clause license.