Injection
is a tiny utility to help managing dependency injection with SwiftUI.
You shouldn't 😅 there's plenty of dependency injection libraries for swift out there - by no means is this intended to replace any of those. For my personal use cases, there's two main intents:
- Simplify adding custom
EnvironmentValues
- Be able to use a similar api to
EnvironmentValues
for objects that aren't meant to beObservable
or should not belong in theView
'sEnvironmentValues
import Injection
struct DependencyOne { ... }
struct DependencyTwo { ... }
// 1: Add the @Inject macro to the extension
@Inject
extension EnvironmentValues {
var dep1 = DependencyOne()
var dep2 = DependencyTwo()
}
// 2: Use it normally with the @Environment property wrapper
struct ExampleView: View {
@Environment(\.dep1) var dep1
@Environment(\.dep2) var dep2
var body: some View { ... }
}
The same logic also applies to the simpler container DependencyValues
:
import Injection
struct DependencyOne { ... }
struct DependencyTwo { ... }
// 1: Add the @Inject macro to the extension
@Inject
extension DependencyValues {
var dep1 = DependencyOne()
var dep2 = DependencyTwo()
}
// (optionally) set it elsewhere in the view hierarchy
@main
struct ExampleApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.dependency(\.dep1, DependencyOne())
}
}
}
// 2: Use it with the @Dependency property wrapper
struct ExampleView: View {
@Dependency(\.dep1) var dep1
@Dependency(\.dep2) var dep2
var body: some View { ... }
}
If you're working directly in a Package, add Injection to your Package.swift file
dependencies: [
.package(url: "https://github.com/JARMourato/Injection.git", .upToNextMajor(from: "2.0.0" )),
]
If working in an Xcode project select File->Swift Packages->Add Package Dependency...
and search for the package name: Injection
or the git url:
https://github.com/JARMourato/Injection.git
If you feel like something is missing or you want to add any new functionality, please open an issue requesting it and/or submit a pull request with passing tests 🙌
MIT
João (@_JARMourato)