CSLA.NET 6.0.0
CSLA .NET is a software development framework that helps you build a reusable, maintainable object-oriented business layer for your app.
AssemblyReferences.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Concurrent;
3using System.Collections.Generic;
4using System.IO;
5using System.Linq;
6using System.Reflection;
7using Microsoft.CodeAnalysis;
8
10{
11 internal static class AssemblyReferences
12 {
13 private static void LoadDependencies(HashSet<Assembly> loadedAssemblies, Assembly fromAssembly)
14 {
15 foreach (var reference in fromAssembly.GetReferencedAssemblies())
16 {
17 try
18 {
19 var assembly = Assembly.Load(reference);
20
21 if (loadedAssemblies.Add(assembly))
22 {
23 LoadDependencies(loadedAssemblies, assembly);
24 }
25 }
26 catch (FileNotFoundException) { }
27 catch (FileLoadException) { }
28 }
29 }
30
31 internal static MetadataReference[] GetMetadataReferences(IEnumerable<Assembly> assemblies)
32 {
33 var references = assemblyReferences.Value;
34
35 foreach (var reference in assemblies.Transform())
36 {
37 references.Add(reference);
38 }
39
40 foreach(var assembly in assemblies)
41 {
42 var referencedAssemblies = new HashSet<Assembly>();
43 LoadDependencies(referencedAssemblies, assembly);
44
45 foreach(var referencedAssembly in referencedAssemblies.Transform())
46 {
47 references.Add(referencedAssembly);
48 }
49 }
50
51 return references.ToArray();
52 }
53
54 private static readonly ConcurrentDictionary<Assembly, MetadataReference> transformedAssemblies =
55 new ConcurrentDictionary<Assembly, MetadataReference>();
56
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>();
62
63 // Lifted from:
64 // https://github.com/dotnet/roslyn/wiki/Runtime-code-generation-using-Roslyn-compilations-in-.NET-Core-App
65 internal static Lazy<HashSet<MetadataReference>> assemblyReferences =
66 new Lazy<HashSet<MetadataReference>>(() =>
67 {
68 var assemblies = new HashSet<Assembly>();
69
70 var trustedPlatformAssemblies =
71 (AppDomain.CurrentDomain.GetData("TRUSTED_PLATFORM_ASSEMBLIES") as string)?.Split(Path.PathSeparator);
72
73 if (trustedPlatformAssemblies != null)
74 {
75 var platformAssemblyPaths = new HashSet<string>(trustedPlatformAssemblies);
76 var platformAssemblyNames = platformAssemblyPaths.Select(Path.GetFileNameWithoutExtension);
77
78 foreach (var platformAssemblyName in platformAssemblyNames)
79 {
80 if (!string.IsNullOrWhiteSpace(platformAssemblyName))
81 {
82 assemblies.Add(Assembly.Load(new AssemblyName(platformAssemblyName)));
83 }
84 }
85 }
86
87 foreach (var assembly in assemblies.ToList())
88 {
89 LoadDependencies(assemblies, assembly);
90 }
91
92 return new HashSet<MetadataReference>(assemblies.Transform());
93 });
94 }
95}