Skip to content

Instantly share code, notes, and snippets.

@ukitaka
Created June 28, 2016 06:02
Show Gist options
  • Save ukitaka/cefbfcb523b10150dec1eeb3e0dc1ccc to your computer and use it in GitHub Desktop.
Save ukitaka/cefbfcb523b10150dec1eeb3e0dc1ccc to your computer and use it in GitHub Desktop.
Lightweight DI Framework Cleanse memo
// 1. インターフェースをつくる
protocol UserRepository {
func findByID(userID: UserID) -> User
}
// 2. 実装を作る
class UserDAO: UserRepository {
init() { ... }
func findByID(userID: UserID) -> User {
...
}
}
// 3. Moduleを作る
// - 依存として注入されるオブジェクト
// - つまりDependency
struct UserRepositoryModule: Module {
func configure<B : Binder>(binder binder: B) {
// UserRepositoryの実装としてUserDAOを使うよという意味
binder.bind(UserRepository.self).asSingleton().to(factory: UserDAO.init)
}
}
// 4. 注入先のオブジェクトをつくる
class UserListUseCase {
let userRepository: UserRepository
init(userRepository: UserRepository) {
self.userRepository = userRepository
}
}
// 5. Component作成
struct UserListUseCaseComponent: Component {
typealias Root = UserListUseCase
func configure<B : Binder>(binder binder: B) {
binder.install(module: UserRepositoryModule())
// Bind our root object
binder.bind().to(factory: UserListUseCase.init)
}
}
// 6. オブジェクト生成
let useCase: UserListUseCase = try! UserListUseCaseComponent().build()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment