2using System.Collections.Concurrent;
3using System.Collections.Generic;
6using System.Reflection;
11 internal static class AssemblyReferences
13 private static void LoadDependencies(HashSet<Assembly> loadedAssemblies, Assembly fromAssembly)
15 foreach (var reference
in fromAssembly.GetReferencedAssemblies())
19 var assembly = Assembly.Load(reference);
21 if (loadedAssemblies.Add(assembly))
23 LoadDependencies(loadedAssemblies, assembly);
26 catch (FileNotFoundException) { }
27 catch (FileLoadException) { }
31 internal static MetadataReference[] GetMetadataReferences(IEnumerable<Assembly> assemblies)
33 var references = assemblyReferences.Value;
35 foreach (var reference
in assemblies.Transform())
37 references.Add(reference);
40 foreach(var assembly
in assemblies)
42 var referencedAssemblies =
new HashSet<Assembly>();
43 LoadDependencies(referencedAssemblies, assembly);
45 foreach(var referencedAssembly
in referencedAssemblies.Transform())
47 references.Add(referencedAssembly);
51 return references.ToArray();
54 private static readonly ConcurrentDictionary<Assembly, MetadataReference> transformedAssemblies =
55 new ConcurrentDictionary<Assembly, MetadataReference>();
57 private static IEnumerable<MetadataReference> Transform(
this IEnumerable<Assembly> @
this) =>
58 @this.Where(_ => !_.IsDynamic && !
string.IsNullOrWhiteSpace(_.Location))
59 .Select(_ => transformedAssemblies.GetOrAdd(
60 _,
asm => MetadataReference.CreateFromFile(
asm.Location)))
61 .Cast<MetadataReference>();
65 internal static Lazy<HashSet<MetadataReference>> assemblyReferences =
66 new Lazy<HashSet<MetadataReference>>(() =>
68 var assemblies =
new HashSet<Assembly>();
70 var trustedPlatformAssemblies =
71 (AppDomain.CurrentDomain.GetData(
"TRUSTED_PLATFORM_ASSEMBLIES") as string)?.Split(Path.PathSeparator);
73 if (trustedPlatformAssemblies !=
null)
75 var platformAssemblyPaths =
new HashSet<string>(trustedPlatformAssemblies);
76 var platformAssemblyNames = platformAssemblyPaths.Select(Path.GetFileNameWithoutExtension);
78 foreach (var platformAssemblyName
in platformAssemblyNames)
80 if (!
string.IsNullOrWhiteSpace(platformAssemblyName))
82 assemblies.Add(Assembly.Load(
new AssemblyName(platformAssemblyName)));
87 foreach (var assembly
in assemblies.ToList())
89 LoadDependencies(assemblies, assembly);
92 return new HashSet<MetadataReference>(assemblies.Transform());