Dependency Injection

Dependency Injection

Properties

NameDescriptionTypeDefault
containerตัวแปรที่เก็บ Dependency ทั้งหมดของ Service ไว้ โดยสามารถเรียก Dependency ได้ผ่านตัวแปรนี้ContainerContainer ที่ Register Dependency ของ HttpService และ LocalDBService เอาไว้

Method Overview

NameDescriptionReturn
register()การ Register Dependency ของ Service ไว้ใน Containervoid

Method Details

static func register<T>(classProtocol: T.Type, classObject: T)

การ Register Dependency ของ Service ไว้ใน Container

Parameters

NameDescriptionType
TClass ของ ServiceClass
classProtocolProtocol ของ ClassT.Type
classObjectObject ของ ClassT

Example

// Protocol
protocol YourServiceProtocol {
  func yourFunction()
}

// Class
class YourService: NSObject, YourServiceProtocol {

  static let sharedInstance = YourService()
  
  func yourFunction() {}

}

// Register YourService
DI.register(classProtocol: YourServiceProtocol.self, classObject: YourService.sharedInstance)

// Get YourService from container
let yourService = DI.container.resolve(YourServiceProtocol.self)!
// Can call your function
yourService.yourFunction()