DIContainer - A lightweight dependency injection framework for Swift
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
- [Swift 5.7+] Dependency Injection (1) – PropertyWrapper를 이용한 Service Locator 구현하기
- [Swift 5.7+] Dependency Injection (2) – 컨테이너 무결성 보장해 보기
License
MIT license. See the LICENSE file for details.