Awesome Open Source
Awesome Open Source

DIKit

Dependency Injection Framework for Swift, inspired by KOIN. Basically an implementation of service-locator pattern, living within the application's context.

Grow as you go!

We started small, it perfectly fits our use case.

Installation

Via Carthage

DIKit can be installed using Carthage. After installing Carthage just add DIKit to your Cartfile:

github "benjohnde/DIKit" ~> 1.4

Via CocoaPods

CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. After installing CocoaPods add DIKit to your Podfile:

platform :ios, '9.0'
pod 'DIKit', '~> 1.4'

Basic usage

  1. Define some sub DependencyContainer (basically some sort of module declaration):
import DIKit

public extension DependencyContainer {
    static var backend = module {
        single { Backend() as BackendProtocol }
    }
}

public extension DependencyContainer {
    static var network = module {
        single { Network() as NetworkProtocol }
    }
}

public extension DependenyContainer {
    static var app = module {
        single { AppState() as AppStateProtocol }
        factory { StopWatch() as StopWatchProtocol }
    }
}
  1. Set the root DependencyContainer and set it before the application gets initialised:
import DIKit

@UIApplicationMain
class AppDelegate: UIApplicationDelegate {
    override init() {
        super.init()
        DependencyContainer.defined(by: modules { .backend; .network; .app })
    }
}

Without sub DependencyContainer the following shorthand writing also does the job:

import DIKit

@UIApplicationMain
class AppDelegate: UIApplicationDelegate {
    override init() {
        super.init()
        DependencyContainer.defined(by: module {
            single { AppState() as AppStateProtocol }
            factory { StopWatch() as StopWatchProtocol }
        })
    }
}
  1. Inject the dependencies, for instance in a module:
import DIKit

class Backend: BackendProtocol {
    @Inject var network: NetworkProtocol
}

or a ViewController:

import DIKit

class FirstViewController: UIViewController {
    // MARK: - Dependencies
    @LazyInject var backend: BackendProtocol
    @OptionalInject var stopwatch: StopWatchProtocol?

    // MARK: - View lifecycle
    override func viewWillAppear(_ animated: Bool) {
        let result = backend.fetch()
        print(result)
    }
}

Injection via constructor:

import DIKit

struct AppState: AppStateProtocol {
    private let backend: BackendProtocol
    init(backend: BackendProtocol = resolve()) {
        self.backend = backend
    }
}

Get A Weekly Email With Trending Projects For These Topics
No Spam. Unsubscribe easily at any time.
swift (6,639
ios (2,967
cocoapods (510
carthage (304
dependency-injection (175
swift-package-manager (83
swift5 (75
injection (57
helper (38
dependency (19
koin (16
swiftpm (15

Find Open Source By Browsing 7,000 Topics Across 59 Categories