-
Notifications
You must be signed in to change notification settings - Fork 0
Usage
Lucas Deprit edited this page Oct 19, 2024
·
2 revisions
You can register dependencies using singleton or transient scopes.
AppContainer.register(Service.self, scope: .singleton) {
MyService()
}AppContainer.register(Service.self, scope: .transient) {
AnotherService()
}To resolve a dependency, simply call the resolve method on the AppContainer.
let service: Service = AppContainer.resolve(Service.self)For a more seamless dependency injection experience, use the @Inject property wrapper:
class MyViewController {
@Inject var service: Service
func loadData() {
let data = service.getData()
// Use data
}
}You can register multiple implementations of the same protocol using names:
AppContainer.register(Service.self, name: "premiumService") {
PremiumService()
}
let premiumService: Service = AppContainer.resolve(Service.self, name: "premiumService")Here’s a complete example illustrating the setup and usage:
// Define a protocol
protocol Service {
func getData() -> String
}
// Implement the protocol
class MockService: Service {
func getData() -> String {
return "Mocked Data"
}
}
// Register the service
AppContainer.register(Service.self, scope: .singleton) {
MockService()
}
// Use @Inject to access the service
class MyFeature {
@Inject var service: Service
func printData() {
print(service.getData()) // Output: Mocked Data
}
}
// Example usage
let feature = MyFeature()
feature.printData()