private static TemplateDescriptor Compile( string source, IReadOnlyList <MetadataReference> references, AssemblyLoadContext assemblyLoadContext) { var csharpCode = ToCSharp(source); var csharpDocumentAst = CSharpSyntaxTree.ParseText(csharpCode); var csharpDocumentCompilation = CSharpCompilation.Create( $"MiniRazor_Assembly_{Guid.NewGuid()}", new[] { csharpDocumentAst }, references, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); using var assemblyStream = new MemoryStream(); var csharpDocumentCompilationResult = csharpDocumentCompilation.Emit(assemblyStream); if (!csharpDocumentCompilationResult.Success) { throw MiniRazorException.CompilationFailed( csharpCode, csharpDocumentCompilationResult.Diagnostics ); } assemblyStream.Seek(0, SeekOrigin.Begin); var templateAssembly = assemblyLoadContext.LoadFromStream(assemblyStream); var templateType = templateAssembly.GetTypes().FirstOrDefault(t => t.Implements(typeof(ITemplate))) ?? throw new InvalidOperationException("Could not locate compiled template in the generated assembly."); return(new TemplateDescriptor(templateType)); }
private Assembly CompileRazorCode(string assemblyName, RazorCodeDocument codeDocument) { var csharpDocument = codeDocument.GetCSharpDocument(); var csharpDocumentAst = CSharpSyntaxTree.ParseText(csharpDocument.GeneratedCode); var csharpDocumentCompilation = CSharpCompilation.Create( assemblyName, new[] { csharpDocumentAst }, _metadataReferencesLazy.Value, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) ); using var assemblyStream = new MemoryStream(); var csharpDocumentCompilationResult = csharpDocumentCompilation.Emit(assemblyStream); if (!csharpDocumentCompilationResult.Success) { throw MiniRazorException.CompilationFailed( csharpDocument.GeneratedCode, csharpDocumentCompilationResult.Diagnostics ); } assemblyStream.Seek(0, SeekOrigin.Begin); return(_assemblyLoadContext.LoadFromStream(assemblyStream)); }