-
Notifications
You must be signed in to change notification settings - Fork 0
/
RazorComponentClientModuleCollection.cs
220 lines (189 loc) · 8.24 KB
/
RazorComponentClientModuleCollection.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
using Microsoft.AspNetCore.Components.WebAssembly.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.JSInterop;
using Modulight.Modules.Client.RazorComponents.UI;
using Modulight.Modules.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
namespace Modulight.Modules.Client.RazorComponents
{
/// <summary>
/// Specifies the contract for razor component module hosts.
/// </summary>
public interface IRazorComponentClientModuleCollection : IModuleCollection<IRazorComponentClientModule, RazorComponentClientModuleManifest>
{
/// <summary>
/// Load related assemblies for a given route.
/// </summary>
/// <param name="path">Route path.</param>
/// <param name="recurse">Load dependent assemblies recursely.</param>
/// <param name="throwOnError">Throw exceptions when error occurs instead of logs.</param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<List<Assembly>> GetAssembliesForRouting(string path, bool recurse = false, bool throwOnError = false, CancellationToken cancellationToken = default);
/// <summary>
/// Validate modules.
/// Check if route roots conflict or assembly loading fails.
/// </summary>
/// <returns></returns>
Task Validate();
/// <summary>
/// Load all <see cref="UIResource"/> defined in modules into DOM.
/// </summary>
/// <returns></returns>
Task LoadResources(Type? moduleType = null);
}
/// <summary>
/// Extension methods for <see cref="IRazorComponentClientModuleCollection"/>.
/// </summary>
public static class RazorComponentClientModuleCollectionExtensions
{
/// <summary>
/// Load all <see cref="UIResource"/> defined in modules into DOM.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="collection"></param>
/// <returns></returns>
public static Task LoadResources<T>(this IRazorComponentClientModuleCollection collection) where T : IModule => collection.LoadResources(typeof(T));
}
internal class RazorComponentClientModuleCollection : ModuleHostFilterCollection<IRazorComponentClientModule, RazorComponentClientModuleManifest>, IRazorComponentClientModuleCollection
{
Dictionary<Type, RazorComponentClientModuleManifest> Manifests { get; } = new Dictionary<Type, RazorComponentClientModuleManifest>();
public RazorComponentClientModuleCollection(IModuleHost host) : base(host)
{
Logger = host.Services.GetRequiredService<ILogger<RazorComponentClientModuleCollection>>();
}
public ILogger<RazorComponentClientModuleCollection> Logger { get; }
public async Task LoadResources(Type? moduleType = null)
{
using var scope = Host.Services.CreateScope();
var provider = scope.ServiceProvider;
var ui = provider.GetRequiredService<ModuleUILoader>();
var targetModules = LoadedModules;
if (moduleType is not null)
{
targetModules = targetModules.Where(x => x.GetType().IsModule(moduleType));
}
foreach (var manifest in Manifests.Values)
{
foreach (var resource in manifest.Resources)
{
try
{
switch (resource.Type)
{
case UIResourceType.Script:
await ui.LoadScript(resource.Path);
break;
case UIResourceType.StyleSheet:
await ui.LoadStyleSheet(resource.Path);
break;
}
}
catch (JSException ex)
{
Logger.LogError(ex, $"Failed to load resource {resource.Path}");
}
}
}
}
public async Task Validate()
{
using var scope = Host.Services.CreateScope();
var provider = scope.ServiceProvider;
HashSet<string> rootPaths = new HashSet<string>();
foreach (var module in LoadedModules)
{
var pages = module.GetPageProvider(Host);
if (pages is not null)
{
if (pages.RootPath is not "")
{
if (rootPaths.Contains(pages.RootPath))
{
throw new Exception($"Same RootPath in modules: {pages.RootPath} @ {module.Manifest.Name}");
}
rootPaths.Add(pages.RootPath);
}
await GetAssembliesForRouting($"/{pages.RootPath}", throwOnError: true);
}
}
}
public async Task<List<Assembly>> GetAssembliesForRouting(string path, bool recurse = false, bool throwOnError = false, CancellationToken cancellationToken = default)
{
using var scope = Host.Services.CreateScope();
var provider = scope.ServiceProvider;
var lazyLoader = provider.GetRequiredService<LazyAssemblyLoader>();
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
List<Assembly> results = new List<Assembly>();
Queue<string> toLoad = new Queue<string>();
foreach (var module in LoadedModules)
{
cancellationToken.ThrowIfCancellationRequested();
toLoad.Enqueue(module.GetType().GetAssemblyName());
var pages = module.GetPageProvider(Host);
if (pages is null || pages is not null && pages.Contains(path))
{
foreach (var resource in GetManifest(module.GetType()).Resources.Where(x => x.Type is UIResourceType.Assembly))
{
cancellationToken.ThrowIfCancellationRequested();
toLoad.Enqueue(resource.Path);
}
}
}
while (toLoad.Count > 0)
{
cancellationToken.ThrowIfCancellationRequested();
var current = toLoad.Dequeue();
Assembly? assembly;
assembly = loadedAssemblies.FirstOrDefault(x => x.GetName().Name == current);
if (assembly is null)
{
try
{
// Logger.LogInformation($"Loading assembly {current}");
assembly = Environment.OSVersion.Platform == PlatformID.Other
? (await lazyLoader.LoadAssembliesAsync(new[] { current + ".dll" })).FirstOrDefault()
: Assembly.Load(current);
}
catch (Exception ex)
{
if (throwOnError)
{
throw;
}
else
{
Logger.LogWarning($"Failed to load assembly {current}: {ex}");
}
}
}
if (assembly is null)
{
if (throwOnError)
{
throw new NullReferenceException($"Failed to load assembly {current}.");
}
Logger.LogError($"Failed to load assembly {current}.");
continue;
}
results.Add(assembly);
if (recurse)
{
foreach (var refe in assembly.GetReferencedAssemblies())
{
cancellationToken.ThrowIfCancellationRequested();
if (refe.Name is not null)
toLoad.Enqueue(refe.Name);
}
}
}
return results;
}
}
}