Is it possible to use the source generators with CSharpCompilation? #626
Unanswered
AndrewKeepCoding
asked this question in
Q&A
Replies: 1 comment 1 reply
-
Hi @AndrewKeepCoding Yes, it is possible to use the source generators with CSharpCompilation. Here's an example of how you can do it: using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
// Define your source generator class
public class MySourceGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
// Initialization logic
}
public void Execute(GeneratorExecutionContext context)
{
// Generation logic
}
}
// Create a compilation with your source generator
var syntaxTree = CSharpSyntaxTree.ParseText("class MyClass {}");
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { syntaxTree },
options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary),
references: new[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location) },
new[] { new MySourceGenerator() });
// Emit the compilation and inspect the results
using var ms = new MemoryStream();
var result = compilation.Emit(ms);
if (result.Success)
{
// Compilation succeeded, do something with the output assembly
var assembly = Assembly.Load(ms.ToArray());
}
else
{
// Compilation failed, handle the error
foreach (var diagnostic in result.Diagnostics)
{
Console.Error.WriteLine(diagnostic);
}
} In the above code, we define a source generator class MySourceGenerator, create a C# syntax tree with a simple class definition, create a CSharpCompilation with the syntax tree and the source generator, and emit the compilation to a memory stream. If the compilation succeeds, we load the resulting assembly from the memory stream. If the compilation fails, we print the compilation errors to the console. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm creating dynamic ViewModels with
INotifyPropertyChanged
and it works, but I wonder if it's possible to use the source generators from the toolkit.Beta Was this translation helpful? Give feedback.
All reactions