Reputation: 1588
I'm trying to some old .net code to .net Core. I'm not too familiar with what i'm converting over, but it's some simple code gen using CodeDom. From what I can tell, this means I need to use Roslyn in .net Core.
This is what I had in the old code:
var thing = new CodeTypeDeclaration("test");
wrapper.IsClass = true;
wrapper.TypeAttributes = TypeAttributes.Public;
AddPropertyHelper(thing, typeof(string), "some_prop");
...
...
...
var compiler = CodeDomProvider.CreateProvider("CSharp");
var options = new CompilerParameters();
options.GenerateExecutable = false;
options.GenerateInMemory = true;
options.OutputAssembly = Path.GetTempFileName();
var results = provider.CompileAssemblyFromDom(options);
return results.CompiledAssembly.GetType(GeneratedNamespace + "." + "test");
and this is what I have so far in Roslyn:
var @namespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(GeneratedNamespace));
var classDeclaration = SyntaxFactory.ClassDeclaration("test");
classDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));
AddPropertyToWrapped(classDeclaration, typeof(string), "some_prop");
Edit: this is what i've added
---
var cu = SyntaxFactory.CompilationUnit();
cu.AddMembers(@namespace);
var compilation = CSharpCompilation.Create(
"foo",
syntaxTrees: new[] { cu.SyntaxTree },
options: options,
references: new[] {
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(typeof(Uri).GetTypeInfo().Assembly.Location),
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "mscorlib.dll"),
MetadataReference.CreateFromFile(coreDir.FullName + Path.DirectorySeparatorChar + "System.Runtime.dll")
});
var ms = new MemoryStream();
var emitResult = compilation.Emit(ms);
---
I don't see anything about "compiling" it though. I haven't find any useful examples online or documentation that wasn't just overly complex. Is there something simple i'm missing?
Upvotes: 0
Views: 741
Reputation: 888047
You're looking for the CSharpCompilation.Create()
method, which takes SyntaxTrees and references.
You can then call its various Emit()
methods to compile to a stream.
Upvotes: 1