forked from ssannandeji/Zenject-2019
/
SceneContext.cs
364 lines (297 loc) · 11.4 KB
/
SceneContext.cs
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#if !NOT_UNITY3D
using System;
using System.Collections.Generic;
using System.Linq;
using ModestTree;
using ModestTree.Util;
using UnityEngine;
using UnityEngine.Serialization;
using Zenject.Internal;
namespace Zenject
{
public class SceneContext : RunnableContext
{
public event Action PreInstall;
public event Action PostInstall;
public event Action PreResolve;
public event Action PostResolve;
public static Action<DiContainer> ExtraBindingsInstallMethod;
public static Action<DiContainer> ExtraBindingsLateInstallMethod;
public static IEnumerable<DiContainer> ParentContainers;
[FormerlySerializedAs("ParentNewObjectsUnderRoot")]
[Tooltip("When true, objects that are created at runtime will be parented to the SceneContext")]
[SerializeField]
bool _parentNewObjectsUnderRoot;
[Tooltip("Optional contract names for this SceneContext, allowing contexts in subsequently loaded scenes to depend on it and be parented to it, and also for previously loaded decorators to be included")]
[SerializeField]
List<string> _contractNames = new List<string>();
[Tooltip("Optional contract names of SceneContexts in previously loaded scenes that this context depends on and to which it should be parented")]
[SerializeField]
List<string> _parentContractNames = new List<string>();
DiContainer _container;
readonly List<SceneDecoratorContext> _decoratorContexts = new List<SceneDecoratorContext>();
bool _hasInstalled;
bool _hasResolved;
public override DiContainer Container
{
get { return _container; }
}
public bool HasResolved
{
get { return _hasResolved; }
}
public bool HasInstalled
{
get { return _hasInstalled; }
}
public bool IsValidating
{
get
{
#if UNITY_EDITOR
return ProjectContext.Instance.Container.IsValidating;
#else
return false;
#endif
}
}
public IEnumerable<string> ContractNames
{
get { return _contractNames; }
set
{
_contractNames.Clear();
_contractNames.AddRange(value);
}
}
public IEnumerable<string> ParentContractNames
{
get
{
var result = new List<string>();
result.AddRange(_parentContractNames);
return result;
}
set
{
_parentContractNames = value.ToList();
}
}
public bool ParentNewObjectsUnderRoot
{
get { return _parentNewObjectsUnderRoot; }
set { _parentNewObjectsUnderRoot = value; }
}
public void Awake()
{
#if ZEN_INTERNAL_PROFILING
ProfileTimers.ResetAll();
using (ProfileTimers.CreateTimedBlock("Other"))
#endif
{
Initialize();
}
}
#if UNITY_EDITOR
public void Validate()
{
Assert.That(IsValidating);
Install();
Resolve();
}
#endif
protected override void RunInternal()
{
// We always want to initialize ProjectContext as early as possible
ProjectContext.Instance.EnsureIsInitialized();
#if UNITY_EDITOR
using (ProfileBlock.Start("Zenject.SceneContext.Install"))
#endif
{
Install();
}
#if UNITY_EDITOR
using (ProfileBlock.Start("Zenject.SceneContext.Resolve"))
#endif
{
Resolve();
}
}
public override IEnumerable<GameObject> GetRootGameObjects()
{
return ZenUtilInternal.GetRootGameObjects(gameObject.scene);
}
IEnumerable<DiContainer> GetParentContainers()
{
var parentContractNames = ParentContractNames;
if (parentContractNames.IsEmpty())
{
if (ParentContainers != null)
{
var tempParentContainer = ParentContainers;
// Always reset after using it - it is only used to pass the reference
// between scenes via ZenjectSceneLoader
ParentContainers = null;
return tempParentContainer;
}
return new[] { ProjectContext.Instance.Container };
}
Assert.IsNull(ParentContainers,
"Scene cannot have both a parent scene context name set and also an explicit parent container given");
var parentContainers = UnityUtil.AllLoadedScenes
.Except(gameObject.scene)
.SelectMany(scene => scene.GetRootGameObjects())
.SelectMany(root => root.GetComponentsInChildren<SceneContext>())
.Where(sceneContext => sceneContext.ContractNames.Where(x => parentContractNames.Contains(x)).Any())
.Select(x => x.Container)
.ToList();
if (!parentContainers.Any())
{
throw Assert.CreateException(
"SceneContext on object {0} of scene {1} requires at least one of contracts '{2}', but none of the loaded SceneContexts implements that contract.",
gameObject.name,
gameObject.scene.name,
parentContractNames.Join(", "));
}
return parentContainers;
}
List<SceneDecoratorContext> LookupDecoratorContexts()
{
if (_contractNames.IsEmpty())
{
return new List<SceneDecoratorContext>();
}
return UnityUtil.AllLoadedScenes
.Except(gameObject.scene)
.SelectMany(scene => scene.GetRootGameObjects())
.SelectMany(root => root.GetComponentsInChildren<SceneDecoratorContext>())
.Where(decoratorContext => _contractNames.Contains(decoratorContext.DecoratedContractName))
.ToList();
}
public void Install()
{
#if !UNITY_EDITOR
Assert.That(!IsValidating);
#endif
Assert.That(!_hasInstalled);
_hasInstalled = true;
Assert.IsNull(_container);
var parents = GetParentContainers();
Assert.That(!parents.IsEmpty());
Assert.That(parents.All(x => x.IsValidating == parents.First().IsValidating));
_container = new DiContainer(parents, parents.First().IsValidating);
// Do this after creating DiContainer in case it's needed by the pre install logic
if (PreInstall != null)
{
PreInstall();
}
Assert.That(_decoratorContexts.IsEmpty());
_decoratorContexts.AddRange(LookupDecoratorContexts());
if (_parentNewObjectsUnderRoot)
{
_container.DefaultParent = transform;
}
else
{
_container.DefaultParent = null;
}
// Record all the injectable components in the scene BEFORE installing the installers
// This is nice for cases where the user calls InstantiatePrefab<>, etc. in their installer
// so that it doesn't inject on the game object twice
// InitialComponentsInjecter will also guarantee that any component that is injected into
// another component has itself been injected
var injectableMonoBehaviours = new List<MonoBehaviour>();
GetInjectableMonoBehaviours(injectableMonoBehaviours);
foreach (var instance in injectableMonoBehaviours)
{
_container.QueueForInject(instance);
}
foreach (var decoratorContext in _decoratorContexts)
{
decoratorContext.Initialize(_container);
}
_container.IsInstalling = true;
try
{
InstallBindings(injectableMonoBehaviours);
}
finally
{
_container.IsInstalling = false;
}
if (PostInstall != null)
{
PostInstall();
}
}
public void Resolve()
{
if (PreResolve != null)
{
PreResolve();
}
Assert.That(_hasInstalled);
Assert.That(!_hasResolved);
_hasResolved = true;
_container.ResolveRoots();
if (PostResolve != null)
{
PostResolve();
}
}
void InstallBindings(List<MonoBehaviour> injectableMonoBehaviours)
{
_container.Bind(typeof(Context), typeof(SceneContext)).To<SceneContext>().FromInstance(this);
_container.BindInterfacesTo<SceneContextRegistryAdderAndRemover>().AsSingle();
// Add to registry first and remove from registry last
_container.BindExecutionOrder<SceneContextRegistryAdderAndRemover>(-1);
foreach (var decoratorContext in _decoratorContexts)
{
decoratorContext.InstallDecoratorSceneBindings();
}
InstallSceneBindings(injectableMonoBehaviours);
_container.Bind(typeof(SceneKernel), typeof(MonoKernel))
.To<SceneKernel>().FromNewComponentOn(gameObject).AsSingle().NonLazy();
_container.Bind<ZenjectSceneLoader>().AsSingle();
if (ExtraBindingsInstallMethod != null)
{
ExtraBindingsInstallMethod(_container);
// Reset extra bindings for next time we change scenes
ExtraBindingsInstallMethod = null;
}
// Always install the installers last so they can be injected with
// everything above
foreach (var decoratorContext in _decoratorContexts)
{
decoratorContext.InstallDecoratorInstallers();
}
InstallInstallers();
foreach (var decoratorContext in _decoratorContexts)
{
decoratorContext.InstallLateDecoratorInstallers();
}
if (ExtraBindingsLateInstallMethod != null)
{
ExtraBindingsLateInstallMethod(_container);
// Reset extra bindings for next time we change scenes
ExtraBindingsLateInstallMethod = null;
}
}
protected override void GetInjectableMonoBehaviours(List<MonoBehaviour> monoBehaviours)
{
var scene = gameObject.scene;
ZenUtilInternal.AddStateMachineBehaviourAutoInjectersInScene(scene);
ZenUtilInternal.GetInjectableMonoBehavioursInScene(scene, monoBehaviours);
}
// These methods can be used for cases where you need to create the SceneContext entirely in code
// Note that if you use these methods that you have to call Run() yourself
// This is useful because it allows you to create a SceneContext and configure it how you want
// and add what installers you want before kicking off the Install/Resolve
public static SceneContext Create()
{
return CreateComponent<SceneContext>(
new GameObject("SceneContext"));
}
}
}
#endif