I'm trying to use Roslyn to generate code at runtime in Blazor WASM, however, I am unable to create the MetadataReference
s to the necessary assemblies (namely typeof(object).Assembly
) for the compilation to succeed.
My current code:
var syntaxTree = CSharpSyntaxTree.ParseText("public class Test { }", new(LanguageVersion.Preview));
var comp = CSharpCompilation.Create("MyTestAssembly", new[] { syntaxTree },
new[] { /* ??? */ },
new(OutputKind.DynamicallyLinkedLibrary, concurrentBuild: false));
using var ms = new MemoryStream();
var res = comp.Emit(ms);
/* ... */
Without any MetadataReference
s it tries to compile but fails with several errors about object
not being found properly.
I have tried:
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
, but theLocation
is empty and I could not locate the assemblies in the exposed file system.typeof(object).Assembly.GetType().GetMethod("GetRawData" /* or "GetRawBytes" */, BindingFlags.Instance | BindingFlags.NonPublic)
but it seemsGetRawData
/GetRawBytes
has been removed.var ms = new MemoryStream(); new BinaryFormatter().Serialize(ms, typeof(object).Assembly);
but not only is the binary formatter deprecated, it is also unsupported in Blazor WASM.MetadataReference.CreateFromAssembly
is hard-deprecated and seems to just rely onLocation
internally anyways.
I assume the last resort solution is just manually downloading the .dlls from somewhere and loading them that way, but I'm not sure how well that would work and considering the assemblies are clearly already there, there should definitely be a different way to accomplish this.