I'm dynamically building a class that uses Microsoft.OData.Client this library have references to both mscorlib 2.0.5.0 (i guess the PCL) and 4.0.0.0.
I want to compile my class with roslyn, as part of a larger program, but I can't seem to get it to work. My Roslyn compiler code is pretty minimalistic
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(s);
string assemblyName = Path.GetRandomFileName();
List<MetadataReference> references = new List<MetadataReference>()
{
MetadataReference.CreateFromFile(typeof(DataServiceActionQuery).Assembly.Location),
MetadataReference.CreateFromFile(typeof(ODataAction).Assembly.Location),
MetadataReference.CreateFromFile(typeof(GeneratedCodeAttribute).Assembly.Location),
MetadataReference.CreateFromFile(typeof(IEdmModel).Assembly.Location),
MetadataReference.CreateFromFile(typeof(TimeOfDay).Assembly.Location),
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location),
MetadataReference.CreateFromFile(typeof(XmlDocument).Assembly.Location),
// MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.0\Profile\Profile328\mscorlib.dll")
};
references.AddRange(Directory.GetFiles(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\Facades").Select(f => MetadataReference.CreateFromFile(f)));
var op = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
//op.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
//CSharpCompilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { syntaxTree },
references: references,
options: op);
Assembly assembly = null;
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
//diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
}
else
{
ms.Seek(0, SeekOrigin.Begin);
assembly = Assembly.Load(ms.ToArray());
}
}
These are the errors I get
CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'mscorlib, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes'.
CS0012: The type 'XmlReader' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Xml, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e, Retargetable=Yes'.
DesktopAssemblyIdentityComparer
solved the issue for me once. Note however, thatCSharpCompilationOptions
is immutable as well... have you triedop = op.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)
?