add: Registry
This commit is contained in:
37
GlobalRegistryGenerator.cs
Normal file
37
GlobalRegistryGenerator.cs
Normal file
@@ -0,0 +1,37 @@
|
||||
using System.Text;
|
||||
using Microsoft.CodeAnalysis;
|
||||
|
||||
namespace Hangman.SDK.Generators;
|
||||
[Generator]
|
||||
public class GlobalRegistryGenerator : ISourceGenerator
|
||||
{
|
||||
public void Initialize(GeneratorInitializationContext context)
|
||||
{
|
||||
}
|
||||
|
||||
public void Execute(GeneratorExecutionContext context)
|
||||
{
|
||||
StringBuilder sb = new();
|
||||
sb.AppendLine("using System;");
|
||||
sb.AppendLine("using System.Collections.Generic;");
|
||||
sb.AppendLine("using System.Linq;");
|
||||
sb.AppendLine("using System.Reflection;");
|
||||
sb.AppendLine("using Hangman.SDK.Attributes;");
|
||||
sb.AppendLine("public static partial class GlobalRegistry");
|
||||
sb.AppendLine("{");
|
||||
sb.AppendLine(" public static void Register()");
|
||||
sb.AppendLine(" {");
|
||||
sb.AppendLine(" Assembly assembly = Assembly.GetEntryAssembly();");
|
||||
sb.AppendLine(" IEnumerable<Type> registerTypes = assembly.GetTypes()");
|
||||
sb.AppendLine(" .Where(t => t.IsClass && t.GetCustomAttributes(typeof(AutoRegister), false).Any());");
|
||||
sb.AppendLine(" foreach(Type t in registerTypes)");
|
||||
sb.AppendLine(" {");
|
||||
sb.AppendLine(" MethodInfo registerMethod = t.GetMethod(\"Register\", BindingFlags.Static | BindingFlags.Public);");
|
||||
sb.AppendLine(" if (registerMethod != null)");
|
||||
sb.AppendLine(" registerMethod.Invoke(null, null);");
|
||||
sb.AppendLine(" }");
|
||||
sb.AppendLine(" }");
|
||||
sb.AppendLine("}");
|
||||
context.AddSource("GlobalRegistry.g.cs", sb.ToString());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user