mardi 2 avril 2019

How to use the singleton pattern in conjunction with dependency injection?

I have recently heard that using dependency injection is "the only socially acceptable way to use a singleton in today's software development world". I don't necessarily want to debate the accuracy of this statement right now, as it is mostly opinion-based. My goal right now is to understand how exactly I can use dependency injection with the singleton pattern.

For example, in my latest iOS app, I have a Service layer where I keep my URLSession code. I created this layer as a singleton:

struct ServiceSingleton {

    private init()

    static let shared = ServiceSingleton()

    func fetchJSON() {
     // URLSession code
    }

}

I then use shared in my ViewController, as below:

class ViewController: UIViewController() {

    override viewDidLoad() {
        super.viewDidLoad()

        fetchData()    

    }

    fileprivate func fetchData() {

        ServiceSingleton.shared.fetchJSON()
    }

}

Of course, the code above uses a singleton, but it does not use dependency injection. I am aware that if I wanted to use dependency injection in general, I would add something like this to ViewController:

// Dependency Injection Constructor
override init(someProperty: SomePropertyType) {
    self.someProperty = someProperty
    super.init()
}

TL;DR:

(1) Could you show me how to properly use dependency injection with the singleton pattern in Swift?

(2) Could you explain to me what this achieves?

(3) Should I always use DI when I use the singleton pattern in my iOS projects from now on?

Aucun commentaire:

Enregistrer un commentaire