Skip to content

Commit d4b3f7a

Browse files
committed
unload assemblies when done with them
1 parent d5f98f0 commit d4b3f7a

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

Diff for: LearnJsonEverything/Services/CompilationHelpers.cs

+11-6
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
using Json.Schema.Generation.XmlComments;
22
using Microsoft.CodeAnalysis;
33
using Microsoft.CodeAnalysis.CSharp;
4-
using System.Reflection;
5-
using Json.Schema.Generation;
4+
using System.Runtime.Loader;
65
using static LearnJsonEverything.Services.Iconography;
76

87
namespace LearnJsonEverything.Services;
98

109
public static class CompilationHelpers
1110
{
11+
private static AssemblyLoadContext? _assemblyLoadContext;
1212
private static MetadataReference[]? _references;
1313
private static bool _isLoading;
1414

@@ -106,21 +106,26 @@ public static (ILessonRunner<T>?, string[]) GetRunner<T>(LessonData lesson)
106106
return (null, [.. diagnostics]);
107107
}
108108

109+
dllStream.Position = 0;
110+
pdbStream.Position = 0;
111+
xmlStream.Position = 0;
112+
109113
#pragma warning disable IL2026
110114
#pragma warning disable IL2072
111115
#pragma warning disable IL2070
112-
#pragma warning disable CS0618
113-
var assembly = Assembly.Load(dllStream.ToArray());
116+
_assemblyLoadContext?.Unload();
117+
_assemblyLoadContext = new AssemblyLoadContext(nameof(CompilationHelpers), true);
118+
var assembly = _assemblyLoadContext.LoadFromStream(dllStream, pdbStream);
114119

115-
xmlStream.Position = 0;
116120
using var reader = new StreamReader(xmlStream);
117121
var xmlContent = reader.ReadToEnd();
122+
#pragma warning disable CS0618
118123
DocXmlReader.ExplicitlyAddAssemblyXml(assembly, xmlContent);
124+
#pragma warning restore CS0618
119125

120126

121127
var type = assembly.DefinedTypes.Single(x => !x.IsInterface && x.ImplementedInterfaces.Contains(typeof(ILessonRunner<T>)));
122128
var runner = (ILessonRunner<T>)Activator.CreateInstance(type)!;
123-
#pragma warning restore CS0618
124129
#pragma warning restore IL2070
125130
#pragma warning restore IL2072
126131
#pragma warning restore IL2026

0 commit comments

Comments
 (0)