tomoyasuzuki / Memo

0 stars 0 forks source link

Dependency Injection & Swinject #3

Open tomoyasuzuki opened 4 years ago

tomoyasuzuki commented 4 years ago

DI Container

・Service → 型 ・Component → 実際のオブジェクト ・Factory → コンポーネントを作る場所 SwinjectではContainerに抽象的な型を登録し、factoryで関連するcomponentのインスタンス化をする。

tomoyasuzuki commented 4 years ago

ServiceEntryProtocol

registerされたサービスを元にインスタンスを作成し、storageにインスタンスを格納する。 Containerが作成されると同時にstorageが作成され、インスタンスが保管される。

internal protocol ServiceEntryProtocol: AnyObject {
    func describeWithKey(_ serviceKey: ServiceKey) -> String
    var objectScope: ObjectScopeProtocol { get }
    var storage: InstanceStorage { get }
    var factory: FunctionType { get }
    var initCompleted: (FunctionType)? { get }
    var serviceType: Any.Type { get }
}

InstanceStorage

インスタンスの格納・取り出しに関連するプロトコル。

public protocol InstanceStorage: AnyObject {
    var instance: Any? { get set }
    func graphResolutionCompleted()
    func instance(inGraph graph: GraphIdentifier) -> Any?
    func setInstance(_ instance: Any?, inGraph graph: GraphIdentifier)
}