lundi 16 avril 2018

Dependency Injection in Swift

I completely fell in love with Dependency Injection. I enjoy the way it gives you the possibility to follow SOLID principles, the way it prevents Spaghetti Code. I used Dagger in one of my Android project and everything is more clean, modular and testable. Now I'm working on a Swift project. I would like to follow this kind of design pattern without using any third-party libraries (due to lacks of the current codebase and project commitments). So, I decided to create an homemade implementation.

import UIKit

class DependencyContainer {
    private var dependencies = [String: AnyObject]()

    struct Static {
        static var instance: DependencyContainer?
    }

    static var shared: DependencyContainer {
        if Static.instance == nil {
            Static.instance = DependencyContainer()
        }

        return Static.instance!
    }

    init() {
        AppDelegate.print("Dependency container instantiated")
    }

    func resolve(_ classIdentifier: String) -> AnyObject {
        if dependencies[classIdentifier] == nil {
            dependencies[classIdentifier] = getClassInstance(classIdentifier)
        }

        return dependencies[classIdentifier]!
    }

    private func getClassInstance(_ classIdentifier: String) -> AnyObject {
        var instance: AnyObject! = nil
        let classInstance = NSClassFromString(classIdentifier) as! NSObject.Type
        instance = classInstance.init()

        return instance
    }

    func dispose() {
        DependencyContainer.Static.instance = nil
    }
}

Where I need to inject a dependency I do it as follows:

dataRepository = DependencyContainer.shared.resolve(NSStringFromClass(DataRepositoryImplementation)) as! DataRepository

Everything is working fine at the moment but I think that there are lots of limitations with this kind of approach. Do you have any suggestions?

Aucun commentaire:

Enregistrer un commentaire