-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathModuleCatalogBase.cs
380 lines (334 loc) · 14.9 KB
/
ModuleCatalogBase.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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Globalization;
using System.Linq;
using Prism.Properties;
namespace Prism.Modularity
{
/// <summary>
/// The <see cref="ModuleCatalogBase"/> holds information about the modules that can be used by the
/// application. Each module is described in a <see cref="IModuleInfo"/> class, that records the
/// name, type and location of the module.
///
/// It also verifies that the <see cref="ModuleCatalogBase"/> is internally valid. That means that
/// it does not have:
/// <list>
/// <item>Circular dependencies</item>
/// <item>Missing dependencies</item>
/// <item>
/// Invalid dependencies, such as a Module that's loaded at startup that depends on a module
/// that might need to be retrieved.
/// </item>
/// </list>
/// The <see cref="ModuleCatalogBase"/> also serves as a baseclass for more specialized Catalogs .
/// </summary>
public class ModuleCatalogBase : IModuleCatalog
{
private ModuleCatalogItemCollection _items { get; }
private bool _isLoaded;
/// <summary>
/// Initializes a new instance of the <see cref="IModuleCatalog"/> class.
/// </summary>
public ModuleCatalogBase()
{
_items = new ModuleCatalogItemCollection();
_items.CollectionChanged += ItemsCollectionChanged;
}
/// <summary>
/// Initializes a new instance of the <see cref="IModuleCatalog"/> class while providing an
/// initial list of <see cref="IModuleInfo"/>s.
/// </summary>
/// <param name="modules">The initial list of modules.</param>
public ModuleCatalogBase(IEnumerable<IModuleInfo> modules)
: this()
{
if (modules == null) throw new ArgumentNullException(nameof(modules));
foreach (IModuleInfo moduleInfo in modules)
{
Items.Add(moduleInfo);
}
}
/// <summary>
/// Gets the items in the <see cref="IModuleCatalog"/>. This property is mainly used to add <see cref="IModuleInfoGroup"/>s or
/// <see cref="IModuleInfo"/>s through XAML.
/// </summary>
/// <value>The items in the catalog.</value>
public Collection<IModuleCatalogItem> Items => _items;
/// <summary>
/// Gets all the <see cref="IModuleInfo"/> classes that are in the <see cref="IModuleCatalog"/>, regardless
/// if they are within a <see cref="IModuleInfoGroup"/> or not.
/// </summary>
/// <value>The modules.</value>
public virtual IEnumerable<IModuleInfo> Modules => GrouplessModules.Union(Groups.SelectMany(g => g));
/// <summary>
/// Gets the <see cref="IModuleInfoGroup"/>s that have been added to the <see cref="IModuleCatalog"/>.
/// </summary>
/// <value>The groups.</value>
public IEnumerable<IModuleInfoGroup> Groups => Items.OfType<IModuleInfoGroup>();
/// <summary>
/// Gets or sets a value that remembers whether the <see cref="ModuleCatalogBase"/> has been validated already.
/// </summary>
protected bool Validated { get; set; }
/// <summary>
/// Returns the list of <see cref="IModuleInfo"/>s that are not contained within any <see cref="IModuleInfoGroup"/>.
/// </summary>
/// <value>The groupless modules.</value>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Groupless")]
protected IEnumerable<IModuleInfo> GrouplessModules => Items.OfType<IModuleInfo>();
/// <summary>
/// Loads the catalog if necessary.
/// </summary>
public virtual void Load()
{
_isLoaded = true;
InnerLoad();
}
/// <summary>
/// Return the list of <see cref="IModuleInfo"/>s that <paramref name="moduleInfo"/> depends on.
/// </summary>
/// <remarks>
/// If the <see cref="IModuleCatalog"/> was not yet validated, this method will call <see cref="Validate"/>.
/// </remarks>
/// <param name="moduleInfo">The <see cref="IModuleInfo"/> to get the </param>
/// <returns>An enumeration of <see cref="IModuleInfo"/> that <paramref name="moduleInfo"/> depends on.</returns>
public virtual IEnumerable<IModuleInfo> GetDependentModules(IModuleInfo moduleInfo)
{
this.EnsureCatalogValidated();
return this.GetDependentModulesInner(moduleInfo);
}
/// <summary>
/// Returns a list of <see cref="IModuleInfo"/>s that contain both the <see cref="IModuleInfo"/>s in
/// <paramref name="modules"/>, but also all the modules they depend on.
/// </summary>
/// <param name="modules">The modules to get the dependencies for.</param>
/// <returns>
/// A list of <see cref="IModuleInfo"/> that contains both all <see cref="IModuleInfo"/>s in <paramref name="modules"/>
/// but also all the <see cref="IModuleInfo"/> they depend on.
/// </returns>
public virtual IEnumerable<IModuleInfo> CompleteListWithDependencies(IEnumerable<IModuleInfo> modules)
{
if (modules == null)
throw new ArgumentNullException(nameof(modules));
EnsureCatalogValidated();
List<IModuleInfo> completeList = new List<IModuleInfo>();
List<IModuleInfo> pendingList = modules.ToList();
while (pendingList.Count > 0)
{
var moduleInfo = pendingList[0];
foreach (var dependency in GetDependentModules(moduleInfo))
{
if (!completeList.Contains(dependency) && !pendingList.Contains(dependency))
{
pendingList.Add(dependency);
}
}
pendingList.RemoveAt(0);
completeList.Add(moduleInfo);
}
IEnumerable<IModuleInfo> sortedList = Sort(completeList);
return sortedList;
}
/// <summary>
/// Validates the <see cref="IModuleCatalog"/>.
/// </summary>
/// <exception cref="ModularityException">When validation of the <see cref="IModuleCatalog"/> fails.</exception>
public virtual void Validate()
{
ValidateUniqueModules();
ValidateDependencyGraph();
ValidateCrossGroupDependencies();
ValidateDependenciesInitializationMode();
Validated = true;
}
/// <summary>
/// Adds a <see cref="IModuleInfo"/> to the <see cref="IModuleCatalog"/>.
/// </summary>
/// <param name="moduleInfo">The <see cref="IModuleInfo"/> to add.</param>
/// <returns>The <see cref="IModuleCatalog"/> for easily adding multiple modules.</returns>
public virtual IModuleCatalog AddModule(IModuleInfo moduleInfo)
{
Items.Add(moduleInfo);
return this;
}
/// <summary>
/// Initializes the catalog, which may load and validate the modules.
/// </summary>
/// <exception cref="ModularityException">When validation of the <see cref="ModuleCatalogBase"/> fails, because this method calls <see cref="Validate"/>.</exception>
public virtual void Initialize()
{
if (!_isLoaded)
{
Load();
}
Validate();
}
/// <summary>
/// Checks for cyclic dependencies, by calling the dependency solver.
/// </summary>
/// <param name="modules">the.</param>
/// <returns></returns>
protected static string[] SolveDependencies(IEnumerable<IModuleInfo> modules)
{
if (modules == null)
throw new ArgumentNullException(nameof(modules));
ModuleDependencySolver solver = new ModuleDependencySolver();
foreach (var data in modules)
{
solver.AddModule(data.ModuleName);
if (data.DependsOn != null)
{
foreach (string dependency in data.DependsOn)
{
solver.AddDependency(data.ModuleName, dependency);
}
}
}
if (solver.ModuleCount > 0)
{
return solver.Solve();
}
return new string[0];
}
/// <summary>
/// Ensures that all the dependencies within <paramref name="modules"/> refer to <see cref="IModuleInfo"/>s
/// within that list.
/// </summary>
/// <param name="modules">The modules to validate modules for.</param>
/// <exception cref="ModularityException">
/// Throws if a <see cref="IModuleInfo"/> in <paramref name="modules"/> depends on a module that's
/// not in <paramref name="modules"/>.
/// </exception>
/// <exception cref="ArgumentNullException">Throws if <paramref name="modules"/> is <see langword="null"/>.</exception>
protected static void ValidateDependencies(IEnumerable<IModuleInfo> modules)
{
if (modules == null)
throw new ArgumentNullException(nameof(modules));
var moduleNames = modules.Select(m => m.ModuleName).ToList();
foreach (var moduleInfo in modules)
{
if (moduleInfo.DependsOn != null && moduleInfo.DependsOn.Except(moduleNames).Any())
{
throw new ModularityException(
moduleInfo.ModuleName,
string.Format(CultureInfo.CurrentCulture, Resources.ModuleDependenciesNotMetInGroup, moduleInfo.ModuleName));
}
}
}
/// <summary>
/// Does the actual work of loading the catalog. The base implementation does nothing.
/// </summary>
protected virtual void InnerLoad()
{
}
/// <summary>
/// Sorts a list of <see cref="IModuleInfo"/>s. This method is called by <see cref="CompleteListWithDependencies"/>
/// to return a sorted list.
/// </summary>
/// <param name="modules">The <see cref="IModuleInfo"/>s to sort.</param>
/// <returns>Sorted list of <see cref="IModuleInfo"/>s</returns>
protected virtual IEnumerable<IModuleInfo> Sort(IEnumerable<IModuleInfo> modules)
{
foreach (string moduleName in SolveDependencies(modules))
{
yield return modules.First(m => m.ModuleName == moduleName);
}
}
/// <summary>
/// Makes sure all modules have an Unique name.
/// </summary>
/// <exception cref="DuplicateModuleException">
/// Thrown if the names of one or more modules are not unique.
/// </exception>
protected virtual void ValidateUniqueModules()
{
List<string> moduleNames = Modules.Select(m => m.ModuleName).ToList();
string duplicateModule = moduleNames.FirstOrDefault(
m => moduleNames.Count(m2 => m2 == m) > 1);
if (duplicateModule != null)
{
throw new DuplicateModuleException(duplicateModule, string.Format(CultureInfo.CurrentCulture, Resources.DuplicatedModule, duplicateModule));
}
}
/// <summary>
/// Ensures that there are no cyclic dependencies.
/// </summary>
protected virtual void ValidateDependencyGraph()
{
SolveDependencies(Modules);
}
/// <summary>
/// Ensures that there are no dependencies between modules on different groups.
/// </summary>
/// <remarks>
/// A groupless module can only depend on other groupless modules.
/// A module within a group can depend on other modules within the same group and/or on groupless modules.
/// </remarks>
protected virtual void ValidateCrossGroupDependencies()
{
ValidateDependencies(GrouplessModules);
foreach (var group in Groups)
{
ValidateDependencies(GrouplessModules.Union(group));
}
}
/// <summary>
/// Ensures that there are no modules marked to be loaded <see cref="InitializationMode.WhenAvailable"/>
/// depending on modules loaded <see cref="InitializationMode.OnDemand"/>
/// </summary>
protected virtual void ValidateDependenciesInitializationMode()
{
var moduleInfo = Modules.FirstOrDefault(
m =>
m.InitializationMode == InitializationMode.WhenAvailable &&
GetDependentModulesInner(m)
.Any(dependency => dependency.InitializationMode == InitializationMode.OnDemand));
if (moduleInfo != null)
{
throw new ModularityException(
moduleInfo.ModuleName,
string.Format(CultureInfo.CurrentCulture, Resources.StartupModuleDependsOnAnOnDemandModule, moduleInfo.ModuleName));
}
}
/// <summary>
/// Returns the <see cref="IModuleInfo"/> on which the received module depends on.
/// </summary>
/// <param name="moduleInfo">Module whose dependant modules are requested.</param>
/// <returns>Collection of <see cref="IModuleInfo"/> dependants of <paramref name="moduleInfo"/>.</returns>
protected virtual IEnumerable<IModuleInfo> GetDependentModulesInner(IModuleInfo moduleInfo)
{
return Modules.Where(dependantModule => moduleInfo.DependsOn.Contains(dependantModule.ModuleName));
}
/// <summary>
/// Ensures that the catalog is validated.
/// </summary>
protected virtual void EnsureCatalogValidated()
{
if (!Validated)
{
Validate();
}
}
private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (Validated)
{
EnsureCatalogValidated();
}
}
private class ModuleCatalogItemCollection : Collection<IModuleCatalogItem>, INotifyCollectionChanged
{
public event NotifyCollectionChangedEventHandler CollectionChanged;
protected override void InsertItem(int index, IModuleCatalogItem item)
{
base.InsertItem(index, item);
RaiseCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
}
protected void RaiseCollectionChanged(NotifyCollectionChangedEventArgs eventArgs)
{
CollectionChanged?.Invoke(this, eventArgs);
}
}
}
}