Search code examples
c#.net-core.net-6.0roslyn

Roslyn compiler does not see references


I'm trying to create a .NET 6.0 app that will be able to compile another .NET 6.0 app. The problem is Roslyn does not seem to see references.

These are some of the errors I received from Roslyn:

Invalid assembly name: The name contains invalid characters.
Cannot find the name of the type or namespace 'List<>'
Cannot find the name of the type or namespace 'Task'
Cannot find the name of the type or namespace 'StreamReader'
Name 'Environment' does not exist in the current context
Name 'String' does not exist in the current context
Name 'Array' does not exist in the current context
Type 'MarshalByRefObject' is defined in an unreferenced assembly. You need to add a reference to the 'System.Runtime' assembly
Type 'Uri' is defined in an unreferenced assembly. You need to add a reference to the 'System.Runtime' assembly

And this is my compiler code:

var syntaxTree = CSharpSyntaxTree.ParseText(source);

var references = new[]
{
    MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
    MetadataReference.CreateFromFile(Path.Combine(dp, "BouncyCastle.Crypto.dll"))
};

var compilation = CSharpCompilation.Create(output)
    .WithOptions(new CSharpCompilationOptions(OutputKind.WindowsApplication))
    .AddReferences(references)
    .AddSyntaxTrees(syntaxTree);

EmitResult emitResult = compilation.Emit(output);

I've already tried something like this:

var references = new[]
{
    MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(HttpClient).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(System.Net.HttpWebRequest).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(System.Text.RegularExpressions.Regex).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(List<>).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(Task).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(StreamReader).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(Environment).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(string).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(MarshalByRefObject).Assembly.Location),
    MetadataReference.CreateFromFile(typeof(Uri).Assembly.Location),
    MetadataReference.CreateFromFile(Path.Combine(dp, "BouncyCastle.Crypto.dll"))
};

but it doesn't seem to work.

Any ideas?


Solution

  • You should not create metadata references that way. Instead, use Basic.Reference.Assemblies.Net60 NuGet package. The GitHub repo README has more instructions on how to use this package, but in short, all you need to do is var references = ReferenceAssemblies.Net60 (and don't forget using Basic.Reference.Assemblies;).