Skip to content
Lucas Deprit edited this page Oct 19, 2024 · 2 revisions

Usage

Registering Dependencies

You can register dependencies using singleton or transient scopes.

Registering a Singleton

AppContainer.register(Service.self, scope: .singleton) {
    MyService()
}

Registering a Transient

AppContainer.register(Service.self, scope: .transient) {
    AnotherService()
}

Resolving Dependencies

To resolve a dependency, simply call the resolve method on the AppContainer.

let service: Service = AppContainer.resolve(Service.self)

Using @Inject Property Wrapper

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
    }
}

Named Dependencies

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")

Complete Example

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()

Clone this wiki locally