经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
c#12 实验特性Interceptor如何使用的一个简单但完整的示例
来源:cnblogs  作者:victor.x.qu  时间:2024/8/7 8:48:33  对本文有异议

一直有很多转载dotnet对Interceptor说明文档的,但鲜有说明Interceptor如何使用的,这里写一篇简单示例来展示一下

c# 12 实验特性Interceptor 是什么?

官方解释如下(其实简单说就是语言特性中内置的静态编织方式的aop功能,不同于其他il修改代码的方式,使用上得结合source generater 来生成代码 )

拦截器是一种方法,该方法可以在编译时以声明方式将对可拦截方法的调用替换为对其自身的调用。 通过让拦截器声明所拦截调用的源位置,可以进行这种替换。 拦截器可以向编译中(例如在源生成器中)添加新代码,从而提供更改现有代码语义的有限能力。

在源生成器中使用拦截器修改现有编译的代码,而非向其中添加代码。 源生成器将对可拦截方法的调用替换为对拦截器方法的调用。

如果你有兴趣尝试拦截器,可以阅读功能规范来了解详细信息。 如果使用该功能,请确保随时了解此实验功能的功能规范中的任何更改。 最终确定功能后将在微软文档站点上添加更多指导。

示例

示例目的

这里我们用一个简单的 static method 作为 我们改写方法内容的目标

  1. public static partial class DBExtensions
  2. {
  3. public static string TestInterceptor<T>(object o)
  4. {
  5. return o.GetType().ToString();
  6. }
  7. }

这样的静态方法,我们假设改写的目标为 返回 o 参数的其中一个string类型的属性值

所以应该可以通过如下的 UT 方法

  1. [Fact]
  2. public void CallNoError()
  3. {
  4. Assert.Equal("sss", DBExtensions.TestInterceptor<AEnum>(new { A = "sss", C= "ddd" }));
  5. }

如何实现

第一步 建立类库

建立一个 netstandard2.0 的类库并设置如下

  1. <Project Sdk="Microsoft.NET.Sdk">
  2. <PropertyGroup>
  3. <TargetFramework>netstandard2.0</TargetFramework>
  4. <LangVersion>preview</LangVersion>
  5. <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
  6. <!-- Generates a package at build -->
  7. <IncludeBuildOutput>false</IncludeBuildOutput>
  8. <!-- Do not include the generator as a lib dependency -->
  9. </PropertyGroup>
  10. <ItemGroup>
  11. <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
  12. <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.10.0" PrivateAssets="all"/>
  13. </ItemGroup>
  14. <ItemGroup>
  15. <!-- Package the generator in the analyzer directory of the nuget package -->
  16. <None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />
  17. </ItemGroup>
  18. </Project>

第二步 设置 UT 项目开启 Interceptor 功能

Generated 目录生成代码文件其实是非必须的,但是为了方便大家看到 source generater 生成的代码文件内容,对于我们初次尝试source generater很有帮助

  1. <Project Sdk="Microsoft.NET.Sdk">
  2. <PropertyGroup>
  3. <TargetFramework>net8.0</TargetFramework>
  4. <ImplicitUsings>enable</ImplicitUsings>
  5. <Nullable>enable</Nullable>
  6. <IsPackable>false</IsPackable>
  7. <EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
  8. <CompilerGeneratedFilesOutputPath>Generated</CompilerGeneratedFilesOutputPath>
  9. <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Test.AOT</InterceptorsPreviewNamespaces>
  10. </PropertyGroup>
  11. <ItemGroup>
  12. <ProjectReference Include="..\..\src\SlowestEM.Generator2\SlowestEM.Generator2.csproj" OutputItemType="Analyzer" ReferenceOutputAssembly="true" />
  13. </ItemGroup>
  14. <ItemGroup>
  15. <Using Include="Xunit" />
  16. </ItemGroup>
  17. <Target Name="CleanSourceGeneratedFiles" BeforeTargets="BeforeBuild" DependsOnTargets="$(BeforeBuildDependsOn)">
  18. <RemoveDir Directories="Generated" />
  19. </Target>
  20. <ItemGroup>
  21. <Compile Remove="Generated\**" />
  22. <Content Include="Generated\**" />
  23. </ItemGroup>
  24. </Project>

第三步 实现 InterceptorGenerator

  1. [Generator(LanguageNames.CSharp)]
  2. public class InterceptorGenerator : IIncrementalGenerator
  3. {
  4. }

这里的 IIncrementalGenerator 为source generater 更强设计的一代接口,有更强的性能和更方便的能力, 感兴趣可以参考incremental-generators.md

接着我们来实现接口

  1. [Generator(LanguageNames.CSharp)]
  2. public class InterceptorGenerator : IIncrementalGenerator
  3. {
  4. public void Initialize(IncrementalGeneratorInitializationContext context)
  5. {
  6. var nodes = context.SyntaxProvider.CreateSyntaxProvider(FilterFunc, TransformFunc) // FilterFunc 为遍历语法节点时提供给我们过滤语法节点范围 ,TransformFunc 为我们转换为语法处理数据
  7. .Where(x => x is not null)
  8. .Select((x, _) => x!);
  9. var combined = context.CompilationProvider.Combine(nodes.Collect());
  10. context.RegisterImplementationSourceOutput(combined, Generate); // Generate 是最终实际转换代码文件的方法
  11. }
  12. }

接着我们来实现 FilterFunc

  1. private bool FilterFunc(SyntaxNode node, CancellationToken token) // 这里我们只过滤 调用 TestInterceptor 方法的地方
  2. {
  3. if (node is InvocationExpressionSyntax ie && ie.ChildNodes().FirstOrDefault() is MemberAccessExpressionSyntax ma)
  4. {
  5. return ma.Name.ToString().StartsWith("TestInterceptor");
  6. }
  7. return false;
  8. }
  9. // 可以看出比之前的 ISyntaxContextReceiver 更为简单

接着我们来实现 TransformFunc

  1. private TestData TransformFunc(GeneratorSyntaxContext ctx, CancellationToken token)
  2. {
  3. try
  4. {
  5. // 再次过滤确保只需要处理 方法调用的场景
  6. if (ctx.Node is not InvocationExpressionSyntax ie
  7. || ctx.SemanticModel.GetOperation(ie) is not IInvocationOperation op)
  8. {
  9. return null;
  10. }
  11. // 由于我们测试使用的是 匿名类初始化 语句,参数是 object,所以生成时实际有隐式转换
  12. var s = op.Arguments.Select(i => i.Value as IConversionOperation).Where(i => i is not null)
  13. .Select(i => i.Operand as IAnonymousObjectCreationOperation) // 查找匿名类的第一个 为 string 的属性
  14. .Where(i => i is not null)
  15. .SelectMany(i => i.Initializers)
  16. .Select(i => i as IAssignmentOperation)
  17. .FirstOrDefault(i => i.Target.Type.ToDisplayString() == "string");
  18. // 生成 返回 第一个 为 string 的属性的 方法
  19. return new TestData { Location = op.GetMemberLocation(), Method = @$"
  20. internal static {op.TargetMethod.ReturnType} {op.TargetMethod.Name}_test({string.Join("", op.TargetMethod.Parameters.Select(i => @$"{i.Type} {i.Name}"))})
  21. {{
  22. {(s == null ? "return null;" : $@"
  23. dynamic c = o;
  24. return c.{(s.Target as IPropertyReferenceOperation).Property.Name};
  25. ") }
  26. }}
  27. " };
  28. }
  29. catch (Exception ex)
  30. {
  31. Debug.Fail(ex.Message);
  32. return null;
  33. }
  34. }
  35. // 这里我们随意创建一个类来方便我们处理中间数据
  36. public class TestData
  37. {
  38. public Location Location { get; set; }
  39. public string Method { get; set; }
  40. }
  41. public static class TypeSymbolHelper
  42. {
  43. // 获取 语法节点所在文件物理路径
  44. internal static string GetInterceptorFilePath(this SyntaxTree? tree, Compilation compilation)
  45. {
  46. if (tree is null) return "";
  47. return compilation.Options.SourceReferenceResolver?.NormalizePath(tree.FilePath, baseFilePath: null) ?? tree.FilePath;
  48. }
  49. public static Location GetMemberLocation(this IInvocationOperation call)
  50. => GetMemberSyntax(call).GetLocation();
  51. // 很不幸,由于拦截器 替换必须代码文件物理文件位置,行号 列号都必须准确, 比如 xxx.TestInterceptor, 比如要 TestInterceptor 的准确位置, 如果从 xxx. 开始都不正确,编译无法通过
  52. // 所以这里有一个比较繁琐的方法来帮助我们准确找到 位置
  53. public static SyntaxNode GetMemberSyntax(this IInvocationOperation call)
  54. {
  55. var syntax = call?.Syntax;
  56. if (syntax is null) return null!; // GIGO
  57. foreach (var outer in syntax.ChildNodesAndTokens())
  58. {
  59. var outerNode = outer.AsNode();
  60. if (outerNode is not null && outerNode is MemberAccessExpressionSyntax)
  61. {
  62. // if there is an identifier, we want the **last** one - think Foo.Bar.Blap(...)
  63. SyntaxNode? identifier = null;
  64. foreach (var inner in outerNode.ChildNodesAndTokens())
  65. {
  66. var innerNode = inner.AsNode();
  67. if (innerNode is not null && innerNode is SimpleNameSyntax)
  68. identifier = innerNode;
  69. }
  70. // we'd prefer an identifier, but we'll allow the entire member-access
  71. return identifier ?? outerNode;
  72. }
  73. }
  74. return syntax;
  75. }
  76. }

接着我们来实现 Generate

  1. private void Generate(SourceProductionContext ctx, (Compilation Left, ImmutableArray<TestData> Right) state)
  2. {
  3. try
  4. {
  5. // 这里主要是生成 InterceptsLocation
  6. var s = string.Join("", state.Right.Select(i =>
  7. {
  8. var loc = i.Location.GetLineSpan();
  9. var start = loc.StartLinePosition;
  10. return @$"[global::System.Runtime.CompilerServices.InterceptsLocationAttribute({SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(i.Location.SourceTree.GetInterceptorFilePath(state.Left)))},{start.Line + 1},{start.Character + 1})]
  11. {i.Method}";
  12. }));
  13. var ss = $@"
  14. namespace Test.AOT
  15. {{
  16. file static class GeneratedInterceptors
  17. {{
  18. {s}
  19. }}
  20. }}
  21. namespace System.Runtime.CompilerServices
  22. {{
  23. // this type is needed by the compiler to implement interceptors - it doesn't need to
  24. // come from the runtime itself, though
  25. [global::System.Diagnostics.Conditional(""DEBUG"")] // not needed post-build, so: evaporate
  26. [global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = true)]
  27. sealed file class InterceptsLocationAttribute : global::System.Attribute
  28. {{
  29. public InterceptsLocationAttribute(string path, int lineNumber, int columnNumber)
  30. {{
  31. _ = path;
  32. _ = lineNumber;
  33. _ = columnNumber;
  34. }}
  35. }}
  36. }}
  37. ";
  38. ctx.AddSource((state.Left.AssemblyName ?? "package") + ".generated.cs", ss);
  39. }
  40. catch (Exception ex)
  41. {
  42. Debug.Fail(ex.Message);
  43. }
  44. }

目前需要自定义InterceptsLocationAttribute, 所以需要生成一个,

这样做的目前主要是目前还是实验特性 ,api 设计还在变化,并且其实物理文件位置现在已被认可非常不方便,已设计新的方式,但是相关设计还不太方便使用,所以这里我们也还是使用物理位置的方式

感兴趣的童鞋可以参考interceptors.md

最后一步 编译试试

如果我们编译程序,就会看见生成了这样的文件代码

  1. namespace Test.AOT
  2. {
  3. file static class GeneratedInterceptors
  4. {
  5. [global::System.Runtime.CompilerServices.InterceptsLocationAttribute("D:\\code\\dotnet\\SlowestEM\\test\\UT\\GeneratorUT\\StartMethod.cs",26,35)]
  6. internal static string TestInterceptor_test(object o)
  7. {
  8. dynamic c = o;
  9. return c.A;
  10. }
  11. }
  12. }
  13. namespace System.Runtime.CompilerServices
  14. {
  15. // this type is needed by the compiler to implement interceptors - it doesn't need to
  16. // come from the runtime itself, though
  17. [global::System.Diagnostics.Conditional("DEBUG")] // not needed post-build, so: evaporate
  18. [global::System.AttributeUsage(global::System.AttributeTargets.Method, AllowMultiple = true)]
  19. sealed file class InterceptsLocationAttribute : global::System.Attribute
  20. {
  21. public InterceptsLocationAttribute(string path, int lineNumber, int columnNumber)
  22. {
  23. _ = path;
  24. _ = lineNumber;
  25. _ = columnNumber;
  26. }
  27. }
  28. }

如果运行ut ,结果也正确, debug 逐行调试也可看到断点能进入我们 生成的代码文件中

原文链接:https://www.cnblogs.com/fs7744/p/18346094

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号