Reputation: 1785
Roslyn compiler and dynamics --> I'm trying to compile a property only known at runtime.
The code works when compiling in Visual studio. When compiling with Roslyn, the dynamic properties are 'unknown'.
In this example unit test I have a MyObject that inherits from DynamicObject. The properties are provided with a simple KeyValue Dictionary.
When using 'MyObject' in a hardcoded manner, I can call the property Hello. I can actually use any property at compile time.. Unexisting properties would error at runtime. (expected behaviour)
When using 'MyObject' in code passed on to the roslyn compiler, I can't use any property on my dynamic object. Here the property 'Hello' gives me the error:
CS1061 - 'MyObject' does not contain a definition for 'Hello' and no accessible extension method 'Hello' accepting a first argument of type 'MyObject' could be found (are you missing a using directive or an assembly reference?)
What am I missing?
Example unit test:
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Testing {
[TestClass]
public class FullExampleTest {
[TestMethod]
public void HardCoded() {
var map = new Dictionary<string, string>() {
{ "Hello","Foo"},
{ "World","Bar"}
};
dynamic src = new MyObject(map);
Console.WriteLine(src.Hello);
Assert.AreEqual("Foo Bar", $"{src.Hello} {src.World}");
}
[TestMethod]
public void CompileAtRuntime() {
string code = @"
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using Testing;
namespace MyNamespace{{
public class MyClass{{
public static void MyMethod(MyObject src){{
Console.WriteLine(src.Hello);
}}
}}
}}
";
var ns = Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51");
MetadataReference[] references = new MetadataReference[]
{
MetadataReference.CreateFromFile(ns.Location), //netstandard
MetadataReference.CreateFromFile(typeof(Object).Assembly.Location), //mscorlib
MetadataReference.CreateFromFile(typeof(DynamicObject).Assembly.Location), //System.Core
MetadataReference.CreateFromFile(typeof(RuntimeBinderException).Assembly.Location),//Microsoft.CSharp
MetadataReference.CreateFromFile(typeof(Action).Assembly.Location), //System.Runtime
MetadataReference.CreateFromFile(typeof(FullExampleTest).Assembly.Location) // this assembly
};
var comp = CSharpCompilation.Create(
assemblyName: Path.GetRandomFileName(),
syntaxTrees: new[] { CSharpSyntaxTree.ParseText(code) },
references: references,
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)
);
using (var ms = new MemoryStream()) {
var result = comp.Emit(ms);
if (!result.Success) {
var failures = result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures) {
Console.WriteLine($"{diagnostic.Id} - {diagnostic.GetMessage()}");
}
}
Assert.IsTrue(result.Success, "Compilation failure..");
}
}
}
public class MyObject : DynamicObject {
private IDictionary<string, string> _Map;
public MyObject(IDictionary<string, string> map) {
_Map = map;
}
public override bool TryGetMember(GetMemberBinder binder, out object result) {
Contract.Assert(binder != null);
var ret = _Map.TryGetValue(binder.Name, out string value);
result = value;
return ret;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) {
Contract.Assert(binder != null);
var ret = _Map.TryGetValue(binder.Name, out string value);
result = value;
return ret;
}
}
}
Upvotes: 4
Views: 3706
Reputation: 156524
Your dynamically-compiled code is not the same as your statically-compiled code. In your dynamically-compiled code, you've explicitly declared src
as a dynamic
. Your "hard-coded" example tries to treat is as a MyObject
. You'd get the same problem if your hard-coded test looked like this:
var src = new MyObject(map);
Console.WriteLine(src.Hello);
So you can fix this by casting your src
as dynamic
:
public static void MyMethod(MyObject src){
Console.WriteLine(((dynamic)src).Hello);
}
Or by declaring it as dynamic in the first place:
public static void MyMethod(dynamic src){
Console.WriteLine(src.Hello);
}
Upvotes: 4