DIContainer

DIContainer is lightweight dependency injection framework for Swift.

Requirements

  • Swift 5.7+

Installation

DIContainer is available Swift Package Manager.

Swift Package Manager

in Package.swift add the following:

dependencies: [
    // Dependencies declare other packages that this package depends on.
    // .package(url: /* package url */, from: "1.0.0"),
    .package(url: "https://github.com/minsOne/DIContainer.git", from: "1.0.0")
],
targets: [
    .target(
        name: "MyProject",
        dependencies: [..., "DIContainer"]
    )
    ...
]

Basic Usage

First, register a key and module pair to a Container, where the module has concreate type. Key has protocol type, and concreate type is inheriting protocol type

Container {
    Module(AnimalKey.self) { Cat() }
}
.build()

Then get an instance from the container.

@Inject(AnimalKey.self)
var cat: Meow
cat.doSomething() // prints "Meow.."

Where definitions of the protocols and struct are

struct AnimalKey: InjectionKey {
    var type: Meow?
}

protocol Meow {
    func doSomething()
}

struct Cat: Meow {
    func doSomething() {
        print("Meow..")
    }
}

Post

License

MIT license. See the LICENSE file for details.

GitHub

View Github