Tuesday, August 18, 2026
HomeiOS Developmentios - Is it dangerous observe to make use of dependency injection...

ios – Is it dangerous observe to make use of dependency injection to create a singleton object that may then be used all through the app in swift?

[ad_1]

So think about I’ve an object Person like so:

class Person {
  var id: Int
  var identify: String
  var cellphone: String
}

And a few service that will get the small print like so:

protocol UserService {
  func getUser(withID id: Int, completion: @escaping(_ person: Person, _ error: Error) -> Void)
}

after which an API Service

class UserAPIService: UserService {
  func getUser(withID id: Int, completion: @escaping(_ person: Person, _ error: Error) -> Void) {
    // GET USER FROM API HERE
  }
}

And a service for testing

class UserTestService: UserService {
  func getUser(withID id: Int, completion: @escaping(_ person: Person, _ error: Error) -> Void) {
    // RETURN SOME TEST USER HERE
  }
}

Now the apparent implementation right here is in any class that requires the service within the app you create a UserAPIService object and inject it in to make use of. After which in testing you create the UserTestService and inject it in to make use of.

So this implies (for my use case), that each ViewModal which hits this operate, I must create and inject within the service. Now that’s positive, and it appears to be the observe that I see all over the place, however my query is, why not create a singleton on app/check begin in order that I haven’t got to inject it all over the place? For instance, create a singleton occasion of the UserService like so:

fileprivate _current: UserService?

class UserServiceManager {
  static var present: UserService {
    get {
      if let c = _current { return c }
      return UserAPIService() //return some default if not set
    }
    set {
      _current = newVal
    }
  }
}

Then we will set the required utilization in both the App Delegates didFinishLaunchingWithOptions or Checks setUpWithError like so:

func software(_ software: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  UserServiceManager.present = UserAPIService()
  return true
}

and

override func setUpWithError() throws {
  UserServiceManager.present = UserTestService()
}

Now all over the place I exploit it, I needn’t inject it, I can simply use the UserServiceManager.present request. Is that this dangerous observe? And in that case, why? It looks as if a extra DRY model. My solely concern I can see this far is that if I resolve to separate my code into modules, then I must import every module into the AppDelegate.

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments