I'm trying to use Roslyn to execute a block of code that references a PCL library. Both my console application and the PCL library are targeted to .NET 4.5
The syntax tree executes a method in the referenced library that constructs a library class. There should be no .NET 4.0 references.
(5,27): error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Has anyone had issues with PCL and Roslyn, or got it to work before?
MyCompanyApplication:Program.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.IO;
using System.Reflection;
namespace MyCompanyApplication
{
class Program
{
static void Main(string[] args)
{
EmitResult Result;
var Options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
CSharpCompilation Compilation = CSharpCompilation.Create(
assemblyName: Path.GetRandomFileName(),
syntaxTrees: new[] { CSharpSyntaxTree.ParseText(
@"class Test
{
public void Run(MyCompanyLibrary.Class Class)
{
var Label = Class.NewLabel();
}
}") },
references: new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(MyCompanyLibrary.Class).Assembly.Location),
},
options: Options);
Assembly Assembly = null;
using (var Stream = new MemoryStream())
{
Result = Compilation.Emit(Stream);
if (Result.Success)
Assembly = Assembly.Load(Stream.GetBuffer());
}
if (Result.Success)
{
var TestType = Assembly.GetType("Test");
var Instance = TestType.GetConstructor(new Type[0]).Invoke(new object[0]);
var RunMethod = TestType.GetMethod("Run");
RunMethod.Invoke(Instance, new object[] { new MyCompanyLibrary.Class() });
}
else
{
Console.WriteLine("Test (PCL) failed");
Console.ReadLine();
}
}
}
}
class Test
{
public void Run(MyCompanyLibrary.Class Class)
{
var Label = Class.NewLabel();
}
}
MyCompanyLibrary:Class.cs
namespace MyCompanyLibrary
{
public class Class
{
public Class()
{
}
public Label NewLabel()
{
return new Label(this);
}
}
public class Label
{
internal Label(Class Class)
{
this.Class = Class;
}
private Class Class;
}
}
You are adding a reference to object
from your "MyCompanyApplication", which is not a portable class library.
Change this:
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
to this:
MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile7\System.Runtime.dll")