8. Service locator
class ServiceLocator {
static let sharedInstance = ServiceLocator()
func weatherService() -> WeatherService {...}
func settingsService() -> SettingsService {...}
func adService() -> ADService {...}
func analytics() -> Analytics {...}
}
class WeatherViewController {
func update() {
let weatherService =
ServiceLocator.sharedInstance.weatherService
weatherService.loadData { ... }
}
}
8
9. Why Service Locator is bad?
⢠Classes are dependent from Service Locator
⢠Dependencies are hidden in code
⢠Access to all available services of Service Locator
9
11. Dependency Inversion
Principle
⢠High-level modules should not depend on low-level
modules. Both should depend on abstractions.
⢠Abstractions should not depend on details. Details
should depend on abstractions.
11
29. UI & business logic classes
donât know about assembly
⢠How to implement transition from view controller A
to view controller B?
⢠Does A know about B?
⢠Who creates B?
29
36. Typhoon features
⢠Written in Obj-C with extensive usage of runtime
⢠Initializer/Property/Method Injections
⢠Circular Dependency Injection
⢠Storyboards auto-injection support
⢠Modularity
36
40. Obtain built instances from the
assembly
MyTyphoonAssembly *assembly = [[MyTyphoonAssembly new] activated];
UIViewController *weatherVC = [assembly weatherViewController];
40
41. Typhoon cons
⢠Swift classes should be subclassed from
NSObject.
⢠Need to understand how it works internally
⢠No compile time checks
⢠Hard to debug
41
44. Swinject features
⢠Written in Swift for Swift without runtime usage
⢠Initializer/Property/Method Injections
⢠Circular Dependency Injection
⢠Optional storyboards auto-injection extension
⢠Modularity
⢠Thread safety
44
45. Swinject example
let weatherVCID = "WeatherVC";
let container = Container()
container.register(WeatherService.self) { _ in WeatherServiceImpl() }
container.register(UIViewController.self, name: weatherVCID) {
resolver in
let weatherService = resolver.resolve(WeatherService.self)!
return WeatherViewController(weatherService: weatherService)
}
let weatherVC = container.resolve(UIViewController.self,
name: weatherVCID)!
45
46. Swinject cons
⢠Need to understand how it works internally
⢠No compile time checks
46
47. Handmade Assembly vs DI-
frameworks
⢠Try handmade Assembly
⢠Try DI-frameworks
⢠Make your personal choice
47
48. Summary
⢠DI is good, it makes everyone happy
⢠Use DI in your projects
48