Contain 0.3.4

Contain 0.3.4

Maintained by Axel Ancona Esselmann.



Contain 0.3.4

  • By
  • anconaesselmann

Contain

Contain is a lightweight dependency injection framework for IOS projects. It is written is swift.

Installation

Contain is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'Contain'

How to use Contain

Create a container instance inside your AppDelegate:

import UIKit
import Contain

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var container: ContainerProtocol?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        container = Container(appDelegate: self)
        return true
    }
}

When working without storyboards inject the container into the root view controller and pass it along from there.

When working with storyboards, access the container on the AppDelegate inside the application's first screen:

guard let container = (UIApplication.shared.delegate as? AppDelegate)?.container else {
    return
}

and pass it along from there.

To create a new dependency add a consumer in Consumers.swift:

protocol MyClassConsumer: class {
    var myClass: MyClass? { get set }
}

MyClass either needs to inherit from BaseInjectable or adhere to the Injectable protocol. Note: When adhering to Injectable make sure to follow the constructor pattern used in BaseInjectable.

Any consumer of a dependency just has to inherit from BaseInjectable or adhere to the Injectable protocol and adhere to the desired Consumer protocol.

Example for MyClassConsumer:

class MyClass: BaseInjectable {

}

class MyViewModel: BaseInjectable, MyClassConsumer {
    var myClass: MyClass?
}

MyViewModel can now be injected with the container, and myClass will get assigned inside MyViewModel's initializer.

If the container was injected into the view controller's initializer, view models can be initialized as follows:

lazy var viewModel: { MyViewModel(container: container) }()

Author

anconaesselmann, [email protected]

License

Contain is available under the MIT license. See the LICENSE file for more info.