This is a follow up on Cannot compile a Razor document. I get several errors while compiling a Razor content (not a file). The code is like this:
var content = File.ReadAllText("RazorComponent.razor");
var assemblyName = "RazorComponent";
var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location)!;
var document = RazorSourceDocument.Create(content, assemblyName + ".razor");
var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(Assembly.GetExecutingAssembly().Location),
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(IComponent).Assembly.Location),
MetadataReference.CreateFromFile(typeof(RazorCompiledItemAttribute).Assembly.Location),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "mscorlib.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Core.dll")),
MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll"))
};
var engine = RazorProjectEngine.Create(
RazorConfiguration.Default,
RazorProjectFileSystem.Create("."),
builder =>
{
builder.ConfigureClass((doc, node) =>
{
node.BaseType = typeof(ComponentBase).FullName;
});
});
var codeDocument = engine.Process(source: document, fileKind: null, importSources: [], tagHelpers: []);
var csDocument = codeDocument.GetCSharpDocument();
var syntaxTree = CSharpSyntaxTree.ParseText(csDocument.GeneratedCode);
var compilation = CSharpCompilation.Create(assemblyName, [syntaxTree], references, options);
using var assemblyStrean = new MemoryStream();
var result = compilation.Emit(assemblyStrean);
This does not success result.Success is false and I get several errors:
error CS0115: 'Template.ExecuteAsync()': no suitable method found to override
error CS0103: The name 'WriteLiteral' does not exist in the current context
error CS0103: The name 'Write' does not exist in the current context
Inspecting the generated code, I see that the generated class is called Template, inherits from ComponentBase, and is trying to override an non-existing method called ExecuteAsync. Inside of it is where it's calling Write and WriteLiteral, which, of course, don't exist too.
What am I missing?