C# 12 中的 Interceptor 特性
💡
原文中文,约10200字,阅读约需25分钟。
📝
内容提要
C# 12引入Interceptor特性实现简单AOP逻辑,结合source generator动态生成interceptor,但目前只能intercept正在编译的代码,不能完全作为AOP框架。
🎯
关键要点
- C# 12 引入了 Interceptor 特性,可以实现简单的 AOP 逻辑。
- Interceptor 特性在 .NET 8 的 ASP.NET Core 中也被使用。
- 需要在项目文件中添加配置以支持 Interceptor,RC2 版本不再需要旧配置。
- 手动声明 InterceptsLocationAttribute 来指定拦截方法的位置。
- Interceptor 方法上添加 InterceptsLocation attribute,参数包括文件路径、行数和字符位置。
- 可以通过编辑器或 IDE 获取调用所在的行和列。
- 结合 source generator 动态生成 interceptor,可以提高可维护性。
- LoggingGenerator 通过 source generator 生成 interceptor 的示例代码。
- 生成的代码中,InterceptsLocationAttribute 使用 file 关键词避免与其他类库冲突。
- 目前 interceptor 只能拦截正在编译的代码,且仅支持方法,尚不能完全作为 AOP 框架。
- dotnet 支持 CallerFilePath 和 CallerLineNumber,但不支持获取字符位置,已有请求添加 CallerCharacterNumber attribute。
➡️