-
Notifications
You must be signed in to change notification settings - Fork 87
/
PartDiscovery.cs
698 lines (600 loc) · 30.9 KB
/
PartDiscovery.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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.Composition
{
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Microsoft.VisualStudio.Composition.Reflection;
public abstract class PartDiscovery
{
protected PartDiscovery(Resolver resolver)
{
Requires.NotNull(resolver, nameof(resolver));
this.Resolver = resolver;
}
public Resolver Resolver { get; }
/// <summary>
/// Creates an aggregate <see cref="PartDiscovery"/> instance that delegates to a series of other part discovery extensions.
/// The <see cref="Resolver.DefaultInstance"/> is used.
/// </summary>
/// <inheritdoc cref="Combine(Resolver, PartDiscovery[])"/>
public static PartDiscovery Combine(params PartDiscovery[] discoveryMechanisms)
{
return Combine(Resolver.DefaultInstance, discoveryMechanisms);
}
/// <summary>
/// Creates an aggregate <see cref="PartDiscovery"/> instance that delegates to a series of other part discovery extensions.
/// </summary>
/// <param name="resolver">The <see cref="Composition.Resolver"/> that the aggregate PartDiscovery instance should use.</param>
/// <param name="discoveryMechanisms">The discovery extensions to use. In some cases, extensions defined earlier in the list are preferred.</param>
/// <returns>The aggregate <see cref="PartDiscovery"/> instance.</returns>
public static PartDiscovery Combine(Resolver resolver, params PartDiscovery[] discoveryMechanisms)
{
Requires.NotNull(discoveryMechanisms, nameof(discoveryMechanisms));
foreach (PartDiscovery item in discoveryMechanisms)
{
Requires.Argument(item is object, nameof(discoveryMechanisms), Strings.AllValuesMustBeNonNull);
}
if (discoveryMechanisms.Length == 1 && ReferenceEquals(discoveryMechanisms[0].Resolver, resolver))
{
return discoveryMechanisms[0];
}
return new CombinedPartDiscovery(resolver, discoveryMechanisms);
}
/// <summary>
/// Reflects on a type and returns metadata on its role as a MEF part, if applicable.
/// </summary>
/// <param name="partType">The type to reflect over.</param>
/// <returns>A new instance of <see cref="ComposablePartDefinition"/> if <paramref name="partType"/>
/// represents a MEF part; otherwise <c>null</c>.</returns>
public ComposablePartDefinition? CreatePart(Type partType)
{
return this.CreatePart(partType, true);
}
public Task<DiscoveredParts> CreatePartsAsync(params Type[] partTypes)
{
return this.CreatePartsAsync(partTypes, CancellationToken.None);
}
public async Task<DiscoveredParts> CreatePartsAsync(IEnumerable<Type> partTypes, CancellationToken cancellationToken = default(CancellationToken))
{
Requires.NotNull(partTypes, nameof(partTypes));
var tuple = this.CreateDiscoveryBlockChain(true, null, cancellationToken);
foreach (Type type in partTypes)
{
await tuple.Item1.SendAsync(type).ConfigureAwait(false);
}
tuple.Item1.Complete();
var parts = await tuple.Item2.ConfigureAwait(false);
return parts;
}
/// <summary>
/// Reflects over an assembly and produces MEF parts for every applicable type.
/// </summary>
/// <param name="assembly">The assembly to search for MEF parts.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A set of generated parts.</returns>
public Task<DiscoveredParts> CreatePartsAsync(Assembly assembly, CancellationToken cancellationToken = default(CancellationToken))
{
Requires.NotNull(assembly, nameof(assembly));
return this.CreatePartsAsync(new[] { assembly }, null, cancellationToken);
}
public abstract bool IsExportFactoryType(Type type);
/// <summary>
/// Reflects over a set of assemblies and produces MEF parts for every applicable type.
/// </summary>
/// <param name="assemblies">The assemblies to search for MEF parts.</param>
/// <param name="progress">An optional way to receive progress updates on how discovery is progressing.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A set of generated parts.</returns>
public async Task<DiscoveredParts> CreatePartsAsync(IEnumerable<Assembly> assemblies, IProgress<DiscoveryProgress>? progress = null, CancellationToken cancellationToken = default(CancellationToken))
{
Requires.NotNull(assemblies, nameof(assemblies));
var tuple = this.CreateAssemblyDiscoveryBlockChain(progress, cancellationToken);
foreach (var assembly in assemblies)
{
await tuple.Item1.SendAsync(assembly).ConfigureAwait(false);
}
tuple.Item1.Complete();
var result = await tuple.Item2.ConfigureAwait(false);
return result;
}
/// <summary>
/// Reflects over a set of assemblies and produces MEF parts for every applicable type.
/// </summary>
/// <param name="assemblyPaths">The paths to assemblies to search for MEF parts.</param>
/// <param name="progress">An optional way to receive progress updates on how discovery is progressing.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A set of generated parts.</returns>
public async Task<DiscoveredParts> CreatePartsAsync(IEnumerable<string> assemblyPaths, IProgress<DiscoveryProgress>? progress = null, CancellationToken cancellationToken = default(CancellationToken))
{
Requires.NotNull(assemblyPaths, nameof(assemblyPaths));
var exceptions = new List<PartDiscoveryException>();
var tuple = this.CreateAssemblyDiscoveryBlockChain(progress, cancellationToken);
var assemblyLoader = new TransformManyBlock<string, Assembly>(
path =>
{
try
{
return new Assembly[] { this.Resolver.AssemblyLoader.LoadAssembly(Utilities.GetAssemblyNameWithCodebasePath(path)) };
}
catch (Exception ex)
{
lock (exceptions)
{
exceptions.Add(new PartDiscoveryException(string.Format(CultureInfo.CurrentCulture, Strings.UnableToLoadAssembly, path), ex) { AssemblyPath = path });
}
return Enumerable.Empty<Assembly>();
}
},
new ExecutionDataflowBlockOptions
{
CancellationToken = cancellationToken,
MaxDegreeOfParallelism = Environment.ProcessorCount,
});
assemblyLoader.LinkTo(tuple.Item1, new DataflowLinkOptions { PropagateCompletion = true });
foreach (var assemblyPath in assemblyPaths)
{
await assemblyLoader.SendAsync(assemblyPath).ConfigureAwait(false);
}
assemblyLoader.Complete();
var result = await tuple.Item2.ConfigureAwait(false);
return result.Merge(new DiscoveredParts(Enumerable.Empty<ComposablePartDefinition>(), exceptions));
}
internal static void GetAssemblyNamesFromMetadataAttributes<TMetadataAttribute>(MemberInfo member, ISet<AssemblyName> assemblyNames)
where TMetadataAttribute : class
{
Requires.NotNull(member, nameof(member));
Requires.NotNull(assemblyNames, nameof(assemblyNames));
foreach (var attribute in member.GetAttributes<Attribute>())
{
Type attrType = attribute.GetType();
if (attrType.GetTypeInfo().IsAttributeDefined<TMetadataAttribute>(inherit: true))
{
assemblyNames.Add(attrType.GetTypeInfo().Assembly.GetName());
}
}
}
protected internal static string GetContractName(Type type)
{
return ContractNameServices.GetTypeIdentity(type);
}
protected internal static Type GetTypeIdentityFromImportingType(Type type, bool importMany)
{
Requires.NotNull(type, nameof(type));
if (importMany)
{
type = GetElementTypeFromMany(type);
}
if (type.IsAnyLazyType() || type.IsExportFactoryTypeV1() || type.IsExportFactoryTypeV2())
{
return type.GetTypeInfo().GenericTypeArguments[0];
}
return type;
}
protected internal static TypeRef GetTypeIdentityFromImportingTypeRef(TypeRef typeRef, bool importMany)
{
Requires.NotNull(typeRef, nameof(typeRef));
if (importMany)
{
typeRef = typeRef.ElementTypeRef;
}
if (typeRef.IsAnyLazyType() || typeRef.IsExportFactoryTypeV1() || typeRef.IsExportFactoryTypeV2())
{
return typeRef.GenericTypeArguments[0];
}
return typeRef;
}
protected internal static Type GetElementTypeFromMany(Type type)
{
Requires.NotNull(type, nameof(type));
if (TryGetElementTypeFromMany(type, out var elementType))
{
return elementType;
}
else
{
throw new ArgumentException(string.Format(Strings.ImportManyOnNonCollectionType, type.FullName), nameof(type));
}
}
internal static bool TryGetElementTypeFromMany(Type type, [NotNullWhen(true)] out Type? elementType)
{
Requires.NotNull(type, nameof(type));
if (type.IsArray)
{
elementType = type.GetElementType()!; // T[] -> T
return true;
}
else
{
// Discover the ICollection<T> or ICollection<Lazy<T, TMetadata>> interface implemented by this type.
var icollectionTypes =
from iface in new[] { type }.Concat(type.GetTypeInfo().ImplementedInterfaces)
let ifaceInfo = iface.GetTypeInfo()
where ifaceInfo.IsGenericType
let genericTypeDef = ifaceInfo.GetGenericTypeDefinition()
where genericTypeDef.Equals(typeof(ICollection<>)) || genericTypeDef.Equals(typeof(IEnumerable<>)) || genericTypeDef.Equals(typeof(IList<>))
select ifaceInfo;
var icollectionType = icollectionTypes.FirstOrDefault();
if (icollectionType != null)
{
elementType = icollectionType.GenericTypeArguments[0];
return true;
}
}
elementType = null;
return false;
}
protected static Type GetImportingSiteTypeWithoutCollection(ImportDefinition importDefinition, Type importingSiteType)
{
Requires.NotNull(importDefinition, nameof(importDefinition));
Requires.NotNull(importingSiteType, nameof(importingSiteType));
return importDefinition.Cardinality == ImportCardinality.ZeroOrMore
? GetElementTypeFromMany(importingSiteType)
: importingSiteType;
}
protected static ConstructorInfo GetImportingConstructor<TImportingConstructorAttribute>(Type type, bool publicOnly)
where TImportingConstructorAttribute : Attribute
{
Requires.NotNull(type, nameof(type));
var ctors = type.GetTypeInfo().DeclaredConstructors.Where(ctor => !ctor.IsStatic && (ctor.IsPublic || !publicOnly));
var taggedCtor = ctors.SingleOrDefault(ctor => ctor.IsAttributeDefined<TImportingConstructorAttribute>());
var defaultCtor = ctors.SingleOrDefault(ctor => ctor.GetParameters().Length == 0);
var importingCtor = taggedCtor ?? defaultCtor;
return importingCtor;
}
protected ImmutableHashSet<IImportSatisfiabilityConstraint> GetMetadataViewConstraints(Type receivingType, bool importMany)
{
Requires.NotNull(receivingType, nameof(receivingType));
var result = ImmutableHashSet.Create<IImportSatisfiabilityConstraint>();
Type elementType = importMany ? PartDiscovery.GetElementTypeFromMany(receivingType) : receivingType;
Type? metadataType = GetMetadataType(elementType);
if (metadataType != null)
{
result = result.Add(ImportMetadataViewConstraint.GetConstraint(TypeRef.Get(metadataType, this.Resolver), this.Resolver));
}
return result;
}
/// <summary>
/// Throws an exception if certain basic rules for an importing member or parameter are violated.
/// </summary>
/// <param name="member">The importing member or importing parameter.</param>
/// <param name="isImportMany">A value indicating whether the import is an ImportMany.</param>
protected virtual void ThrowOnInvalidImportingMemberOrParameter(ICustomAttributeProvider member, bool isImportMany)
{
Requires.NotNull(member, nameof(member));
// Properties with [ImportMany] needn't have a setter (strictly speaking) if the importing constructor
// sets a non-null collection instance to that property. When the collection is pre-created, MEF will just
// add elements to the collection.
if (!isImportMany && member is PropertyInfo importingMember && importingMember.SetMethod == null)
{
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Strings.ImportingPropertyHasNoSetter, importingMember.Name, importingMember.DeclaringType!.FullName));
}
}
/// <summary>
/// Throws an exception if certain basic rules for an exporting member are violated.
/// </summary>
/// <param name="member">The exporting member (or type).</param>
protected virtual void ThrowOnInvalidExportingMember(ICustomAttributeProvider member)
{
Requires.NotNull(member, nameof(member));
if (member is PropertyInfo exportingProperty && exportingProperty.GetMethod == null)
{
throw new NotSupportedException(string.Format(CultureInfo.CurrentCulture, Strings.ExportingPropertyHasNoGetter, exportingProperty.Name, exportingProperty.DeclaringType!.FullName));
}
}
protected internal static ImmutableHashSet<IImportSatisfiabilityConstraint> GetExportTypeIdentityConstraints(Type contractType)
{
Requires.NotNull(contractType, nameof(contractType));
var constraints = ImmutableHashSet<IImportSatisfiabilityConstraint>.Empty;
if (!contractType.IsEquivalentTo(typeof(object)))
{
constraints = constraints.Add(new ExportTypeIdentityConstraint(contractType));
}
return constraints;
}
protected internal static ImmutableDictionary<string, object?> GetImportMetadataForGenericTypeImport(Type contractType)
{
Requires.NotNull(contractType, nameof(contractType));
if (contractType.IsConstructedGenericType)
{
return ImmutableDictionary.Create<string, object?>()
.Add(CompositionConstants.GenericContractMetadataName, GetContractName(contractType.GetGenericTypeDefinition()))
.Add(CompositionConstants.GenericParametersMetadataName, contractType.GenericTypeArguments);
}
else
{
return ImmutableDictionary<string, object?>.Empty;
}
}
/// <summary>
/// Creates an array that contains the contents of a prior array (if any) and one additional element.
/// </summary>
/// <param name="priorArray">The previous version of the array. May be <c>null</c>. This will not be modified by this method.</param>
/// <param name="value">The value to add to the array. May be <c>null</c>.</param>
/// <param name="elementType">The element type for the array, if it is created fresh. May be <c>null</c>.</param>
/// <returns>A new array.</returns>
protected static Array AddElement(Array? priorArray, object? value, Type? elementType)
{
Type? valueType;
Array newValue;
if (priorArray != null)
{
Type priorArrayElementType = priorArray.GetType().GetElementType()!;
valueType = priorArrayElementType == typeof(object) && value != null ? value.GetType() : priorArrayElementType;
newValue = Array.CreateInstance(valueType, priorArray.Length + 1);
Array.Copy(priorArray, newValue, priorArray.Length);
}
else
{
valueType = elementType ?? (value != null ? value.GetType() : typeof(object));
newValue = Array.CreateInstance(valueType, 1);
}
newValue.SetValue(value, newValue.Length - 1);
return newValue;
}
/// <summary>
/// Gets the types to consider for MEF parts.
/// </summary>
/// <param name="assembly">The assembly to read.</param>
/// <returns>A sequence of types.</returns>
protected abstract IEnumerable<Type> GetTypes(Assembly assembly);
/// <summary>
/// Reflects on a type and returns metadata on its role as a MEF part, if applicable.
/// </summary>
/// <param name="partType">The type to reflect over.</param>
/// <param name="typeExplicitlyRequested">A value indicating whether this type was explicitly requested for inclusion in the catalog.</param>
/// <returns>A new instance of <see cref="ComposablePartDefinition"/> if <paramref name="partType"/>
/// represents a MEF part; otherwise <c>null</c>.</returns>
protected abstract ComposablePartDefinition? CreatePart(Type partType, bool typeExplicitlyRequested);
/// <summary>
/// Checks whether an import many collection is creatable.
/// </summary>
internal static bool IsImportManyCollectionTypeCreateable(ImportDefinitionBinding import)
{
Requires.NotNull(import, nameof(import));
return IsImportManyCollectionTypeCreateable(import.ImportingSiteType, import.ImportingSiteTypeWithoutCollection);
}
/// <summary>
/// Checks whether an import many collection is creatable.
/// </summary>
/// <param name="collectionType">The value from ImportingSiteType.</param>
/// <param name="elementType">The value from ImportingSiteTypeWithoutCollection.</param>
/// <returns><c>true</c> if the collection is creatable; <c>false</c> otherwise.</returns>
internal static bool IsImportManyCollectionTypeCreateable(Type collectionType, Type elementType)
{
Requires.NotNull(collectionType, nameof(collectionType));
Requires.NotNull(elementType, nameof(elementType));
var icollectionOfT = typeof(ICollection<>).MakeGenericType(elementType);
var ienumerableOfT = typeof(IEnumerable<>).MakeGenericType(elementType);
var ilistOfT = typeof(IList<>).MakeGenericType(elementType);
if (collectionType.IsArray || collectionType.Equals(ienumerableOfT) || collectionType.Equals(ilistOfT) || collectionType.Equals(icollectionOfT))
{
return true;
}
Verify.Operation(icollectionOfT.GetTypeInfo().IsAssignableFrom(collectionType.GetTypeInfo()), Strings.CollectionTypeMustDeriveFromICollectionOfT);
var defaultCtor = collectionType.GetTypeInfo().DeclaredConstructors.FirstOrDefault(ctor => !ctor.IsStatic && ctor.GetParameters().Length == 0);
if (defaultCtor != null && defaultCtor.IsPublic)
{
return true;
}
return false;
}
/// <summary>
/// Gets the Type of the interface that serves as a metadata view for a given import.
/// </summary>
/// <param name="receivingType">The type of the importing member or parameter, without its ImportMany collection if it had one.</param>
/// <returns>The metadata view, <see cref="IDictionary{String, Object}"/>, or <c>null</c> if there is none.</returns>
private static Type? GetMetadataType(Type receivingType)
{
Requires.NotNull(receivingType, nameof(receivingType));
if (receivingType.IsAnyLazyType() || receivingType.IsExportFactoryType())
{
var args = receivingType.GetTypeInfo().GenericTypeArguments;
if (args.Length == 2)
{
return args[1];
}
}
return null;
}
private Tuple<ITargetBlock<Type>, Task<DiscoveredParts>> CreateDiscoveryBlockChain(bool typeExplicitlyRequested, IProgress<DiscoveryProgress>? progress, CancellationToken cancellationToken)
{
string status = Strings.ScanningMEFAssemblies;
int typesScanned = 0;
var transformBlock = new TransformBlock<Type, object?>(
type =>
{
try
{
return this.CreatePart(type, typeExplicitlyRequested);
}
catch (Exception ex)
{
return new PartDiscoveryException(string.Format(CultureInfo.CurrentCulture, Strings.FailureWhileScanningType, type.FullName), ex) { AssemblyPath = type.GetTypeInfo().Assembly.Location, ScannedType = type };
}
},
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = Debugger.IsAttached ? 1 : Environment.ProcessorCount,
CancellationToken = cancellationToken,
MaxMessagesPerTask = 10,
BoundedCapacity = 100,
});
var parts = ImmutableHashSet.CreateBuilder<ComposablePartDefinition>();
var errors = ImmutableList.CreateBuilder<PartDiscoveryException>();
var aggregatingBlock = new ActionBlock<object?>(partOrException =>
{
var part = partOrException as ComposablePartDefinition;
var error = partOrException as PartDiscoveryException;
Debug.Assert(partOrException is Exception == partOrException is PartDiscoveryException, "Wrong exception type returned.");
if (part != null)
{
parts.Add(part);
}
else if (error != null)
{
errors.Add(error);
}
progress.ReportNullSafe(new DiscoveryProgress(++typesScanned, 0, status));
});
transformBlock.LinkTo(aggregatingBlock, new DataflowLinkOptions { PropagateCompletion = true });
var tcs = new TaskCompletionSource<DiscoveredParts>();
Task forget = Task.Run(async delegate
{
try
{
await aggregatingBlock.Completion.ConfigureAwait(false);
tcs.SetResult(new DiscoveredParts(parts.ToImmutable(), errors.ToImmutable()));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
return Tuple.Create<ITargetBlock<Type>, Task<DiscoveredParts>>(transformBlock, tcs.Task);
}
private Tuple<ITargetBlock<Assembly>, Task<DiscoveredParts>> CreateAssemblyDiscoveryBlockChain(IProgress<DiscoveryProgress>? progress, CancellationToken cancellationToken)
{
var progressFilter = new ProgressFilter(progress);
var tuple = this.CreateDiscoveryBlockChain(false, progressFilter, cancellationToken);
var exceptions = new List<PartDiscoveryException>();
var assemblyBlock = new TransformManyBlock<Assembly, Type>(
a =>
{
IReadOnlyCollection<Type> types;
try
{
// Fully realize any enumerable now so that we can catch the exception rather than
// leave it to dataflow to catch it.
types = this.GetTypes(a).ToList();
}
catch (ReflectionTypeLoadException ex)
{
var partDiscoveryException = new PartDiscoveryException(string.Format(CultureInfo.CurrentCulture, Strings.ReflectionTypeLoadExceptionWhileEnumeratingTypes, a.Location), ex) { AssemblyPath = a.Location };
lock (exceptions)
{
exceptions.Add(partDiscoveryException);
}
types = ex.Types.Where(t => t != null).ToList();
}
catch (Exception ex)
{
var partDiscoveryException = new PartDiscoveryException(string.Format(CultureInfo.CurrentCulture, Strings.UnableToEnumerateTypes, a.Location), ex) { AssemblyPath = a.Location };
lock (exceptions)
{
exceptions.Add(partDiscoveryException);
}
return Enumerable.Empty<Type>();
}
progressFilter.OnDiscoveredMoreTypes(types.Count);
return types;
},
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = Debugger.IsAttached ? 1 : Environment.ProcessorCount,
CancellationToken = cancellationToken,
});
assemblyBlock.LinkTo(tuple.Item1, new DataflowLinkOptions { PropagateCompletion = true });
var tcs = new TaskCompletionSource<DiscoveredParts>();
Task forget = Task.Run(async delegate
{
try
{
var parts = await tuple.Item2.ConfigureAwait(false);
tcs.SetResult(parts.Merge(new DiscoveredParts(Enumerable.Empty<ComposablePartDefinition>(), exceptions)));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
});
return Tuple.Create<ITargetBlock<Assembly>, Task<DiscoveredParts>>(assemblyBlock, tcs.Task);
}
private class ProgressFilter : IProgress<DiscoveryProgress>
{
private readonly IProgress<DiscoveryProgress>? upstreamReceiver;
private int totalTypes;
private DiscoveryProgress lastReportedProgress;
internal ProgressFilter(IProgress<DiscoveryProgress>? upstreamReceiver)
{
this.upstreamReceiver = upstreamReceiver;
}
internal void OnDiscoveredMoreTypes(int count)
{
Interlocked.Add(ref this.totalTypes, count);
}
public void Report(DiscoveryProgress value)
{
if (this.upstreamReceiver != null)
{
// Update with the total types we get out of band.
value = new DiscoveryProgress(value.CompletedSteps, this.totalTypes, value.Status);
bool update = false;
#pragma warning disable CA2002 // Do not lock on objects with weak identity
lock (this)
#pragma warning restore CA2002 // Do not lock on objects with weak identity
{
// Only report progress if completion or status has changed significantly.
if (Math.Abs(value.Completion - this.lastReportedProgress.Completion) > .01 || value.Status != this.lastReportedProgress.Status)
{
this.lastReportedProgress = value;
update = true;
}
}
if (update)
{
this.upstreamReceiver.Report(this.lastReportedProgress);
}
}
}
}
private class CombinedPartDiscovery : PartDiscovery
{
private readonly IReadOnlyList<PartDiscovery> discoveryMechanisms;
internal CombinedPartDiscovery(Resolver resolver, IReadOnlyList<PartDiscovery> discoveryMechanisms)
: base(resolver)
{
Requires.NotNull(discoveryMechanisms, nameof(discoveryMechanisms));
this.discoveryMechanisms = discoveryMechanisms;
}
protected override ComposablePartDefinition? CreatePart(Type partType, bool typeExplicitlyRequested)
{
Requires.NotNull(partType, nameof(partType));
foreach (var discovery in this.discoveryMechanisms)
{
var result = discovery.CreatePart(partType, typeExplicitlyRequested);
if (result != null)
{
return result;
}
}
return null;
}
public override bool IsExportFactoryType(Type type)
{
Requires.NotNull(type, nameof(type));
return this.discoveryMechanisms.Any(discovery => discovery.IsExportFactoryType(type));
}
protected override IEnumerable<Type> GetTypes(Assembly assembly)
{
// Don't ask each PartDiscovery component for types
// because Assembly.GetTypes() is expensive and we don't want to call it multiple times.
// Also, even if the individual modules returned a filtered set of types,
// they'll all see the union of types returned from this method anyway,
// so they have to be prepared for arbitrary types.
return assembly.GetTypes();
}
}
}
}