1

I'm trying to use Roslyn to generate code at runtime in Blazor WASM, however, I am unable to create the MetadataReferences 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 MetadataReferences it tries to compile but fails with several errors about object not being found properly.

I have tried:

  1. MetadataReference.CreateFromFile(typeof(object).Assembly.Location), but the Location is empty and I could not locate the assemblies in the exposed file system.
  2. typeof(object).Assembly.GetType().GetMethod("GetRawData" /* or "GetRawBytes" */, BindingFlags.Instance | BindingFlags.NonPublic) but it seems GetRawData/GetRawBytes has been removed.
  3. 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.
  4. MetadataReference.CreateFromAssembly is hard-deprecated and seems to just rely on Location 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.

Salvage
  • 448
  • 1
  • 4
  • 13

0 Answers0