基于其他程序集类生成源(C# 源生成器)



我想生成一个静态类,该类应该有一个依赖于特定引用程序集中其他类的方法。

一个简化的例子:

// Generator.csproj
[Generator]
public class MyGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
// Register a factory that can create our custom syntax receiver
context.RegisterForSyntaxNotifications(() => new MySyntaxReceiver());
}
public void Execute(GeneratorExecutionContext context)
{
// var syntaxReceiver = (MySyntaxReceiver)context.SyntaxReceiver;
}
}
private class MySyntaxReceiver : ISyntaxReceiver
{
....
}
// Core.csproj
// namespace Core.Entities
class Entity1 : IAccessControl {}
class Entity2  {}
class Entity3 : IAccessControl {}
// Persistence.csproj => has a reference to Core project and the Generator
// this class should be generated ...
static class GeneratedClass
{
public static void DoSomethingEntity1()
public static void DoSomethingEntity3()
}

我想在Core项目中查找Entity类并在Persistence项目中生成一个类, 问题是我的Core项目无法访问,并且在Persistence之前已经编译。我应该使用反射还是手动读取核心实体?或者有没有更好的方法来访问Core项目中的语法树?

因为Core项目已经编译,所以我们无法访问 SyntaxTree,但我们可以通过编译来获取引用的程序集,然后查看这些程序集并找到符号

public void Execute(GeneratorExecutionContext context)
{
// finding Core reference assembly Symbols
IAssemblySymbol assemblySymbol = 
context.Compilation.SourceModule.ReferencedAssemblySymbols.First(q => q.Name == "Core");
// use assembly symbol to get namespace and type symbols
// all members in namespace Core.Entities
var members = assemblySymbol.GlobalNamespace.
GetNamespaceMembers().First(q => q.Name == "Core")                                       
.GetNamespaceMembers().First(q => q.Name == "Entities")
.GetTypeMembers().ToList();
var targets = new HashSet<INamedTypeSymbol>();
// find classes that implemented IAccessControl
foreach (var member in members.Where(m => m.AllInterfaces.Any(i => i.Name == "IAccessControl")))
{
targets.Add(member); // Entity1 Entity3
}

// generate source using targets ...
// context.AddSource("GeneratedClass", source);
}

希望这个例子对其他人有所帮助。

相关内容

  • 没有找到相关文章

最新更新