LightDependency 2.0-beta1

LightDependency 2.0-beta1

Maintained by Aleksey Gotyanov.



LightDependency 2.0-beta1

  • By
  • Gotyanov

Build Status Cocoapods platforms pod Carthage compatible

LightDependency

Inversion of Control Container for Swift

Installation

CocoaPods

# Podfile
use_frameworks!

target 'YOUR_TARGET_NAME' do
    pod 'LightDependency'
end

Replace YOUR_TARGET_NAME and then, in the Podfile directory, run command:

$ pod install

Carthage

Add next line to Cartfile:

github "LightDependency/LightDependency"

Then run:

$ carthage update --platform ios

Usage

Simple example

let container = LightContainer.createRootContainer()
container.configure(defaults: .registerSingletons) { context in
    context.register { MyApiClient() as MyApiClientType }
    context.register { resolver in
        try MyService(apiClient: resolver.resolve())
    }
}

let service: MyService = try container.resolve()

Where definitions of the protocols and classes are:

protocol MyApiClientType {
    // ...
}

final class MyApiClient: MyApiClientType {
    // ...
}

final class MyService {
    init(apiClient: MyApiClientType) {
        // ...
    }

    // ...
}

Example 2

let container = LightContainer.createRootContainer()
container.configure(defaults: .registerSingletons) { context in
    context.register { ItemService() }
        .asDependency(ofType: { $0 as ItemsProvider })
        .asDependency(ofType: { $0 as DetailInfoProvider })
}

container.configure(defaults: .createNewInstancePerResolve) { context in
    context.initContext.register(ItemListViewModel.init)
    context.initContext.register(ItemDetailsViewModel.init)
    context.factoryContext.register(ItemDetailsViewModelFactory.self)
}

let itemListViewModel: ItemListViewModel = try container.resolve()
Definitions

final class ItemService: ItemsProvider, DetailInfoProvider {
    // ...
}

protocol ItemsProvider {
    // ...
}

protocol DetailInfoProvider {
    // ...
}

typealias ItemDetailsViewModelFactory = (ItemModel) -> ItemDetailsViewModel

final class ItemModel {
    // ...
}

final class ItemListViewModel {
    init(itemsProvider: ItemsProvider, itemDetailsFactory: @escaping ItemDetailsViewModelFactory) {
        // ...
    }

    // ...
}

final class ItemDetailsViewModel {
    init(itemModel: ItemModel, detailInfoProvider: DetailInfoProvider) {
        // ...
    }

    // ...
}