-
Notifications
You must be signed in to change notification settings - Fork 666
/
DependencyInjector.swift
64 lines (50 loc) · 1.56 KB
/
DependencyInjector.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// DependencyInjector.swift
// CountriesSwiftUI
//
// Created by Alexey Naumov on 28.10.2019.
// Copyright © 2019 Alexey Naumov. All rights reserved.
//
import SwiftUI
import Combine
// MARK: - DIContainer
struct DIContainer: EnvironmentKey {
let appState: Store<AppState>
let interactors: Interactors
init(appState: Store<AppState>, interactors: Interactors) {
self.appState = appState
self.interactors = interactors
}
init(appState: AppState, interactors: Interactors) {
self.init(appState: Store<AppState>(appState), interactors: interactors)
}
static var defaultValue: Self { Self.default }
private static let `default` = Self(appState: AppState(), interactors: .stub)
}
extension EnvironmentValues {
var injected: DIContainer {
get { self[DIContainer.self] }
set { self[DIContainer.self] = newValue }
}
}
#if DEBUG
extension DIContainer {
static var preview: Self {
.init(appState: .init(AppState.preview), interactors: .stub)
}
}
#endif
// MARK: - Injection in the view hierarchy
extension View {
func inject(_ appState: AppState,
_ interactors: DIContainer.Interactors) -> some View {
let container = DIContainer(appState: .init(appState),
interactors: interactors)
return inject(container)
}
func inject(_ container: DIContainer) -> some View {
return self
.modifier(RootViewAppearance())
.environment(\.injected, container)
}
}