AOP - C# Fody中的方法和属性拦截

本文介绍如何使用Fody与Cauldron.Interception进行AOP编程,包括方法与属性拦截的实现。通过具体代码示例,展示了如何创建方法拦截器和属性设置拦截器,并配置FodyWeavers.xml文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很久很久以前用过postsharp来做AOP, 大家知道的,现在那东东需要付费,于是尝试了一下Fody,但是发现Fody跟新太快了,所以大家在安装fody的时候尽力安装老的版本:packages.config

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Cauldron.Interception.Fody" version="2.0.27" targetFramework="net461" />
  <package id="Costura.Fody" version="1.6.2" targetFramework="net461" developmentDependency="true" />
  <package id="Fody" version="2.5.0" targetFramework="net461" developmentDependency="true" />
</packages>

创建一个方法拦截的demo如下:

using Cauldron.Interception;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FodyTest
{

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public class LoggerAttribute : Attribute, IMethodInterceptor
    {
        private string methodName;

        public void OnEnter(Type declaringType, object instance, MethodBase methodbase, object[] values)
        {
            this.methodName = methodbase.Name;
            this.AppendToFile($"Enter -> {declaringType.Name} {methodbase.Name} {string.Join(" ", values)}");
        }

        public void OnException(Exception e) => this.AppendToFile($"Exception -> {e.Message}");

        public void OnExit() => this.AppendToFile($"Exit -> {this.methodName}");

        private void AppendToFile(string line)
        {
            File.AppendAllLines("log.txt", new string[] { line });
            Console.WriteLine(">> " + line);
        }
    }
}

属性拦截如下:

using Cauldron.Interception;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FodyTest
{

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
    public sealed class OnPropertySetAttribute : Attribute, IPropertySetterInterceptor
    {
        [AssignMethod("{CtorArgument:0}")]
        public Action<string, object> onSetMethod = null;

        public OnPropertySetAttribute(string methodName)
        {
        }

        public void OnException(Exception e)
        {
        }

        public void OnExit()
        {
        }

        public bool OnSet(PropertyInterceptionInfo propertyInterceptionInfo, object oldValue, object newValue)
        {
            this.onSetMethod?.Invoke(propertyInterceptionInfo.PropertyName, newValue);
            return false;
        }
    }
}

创建FodyWeavers.xml:

<?xml version="1.0" encoding="utf-8"?>
<Weavers>
  <Cauldron.Interception />
  <Costura />
</Weavers>

调用code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FodyTest
{
    [OnPropertySet(nameof(ExecuteMe))]
    public class PropertySetterTestClass
    {
        public int BookId { get; set; }
        public string BookName { get; set; }

        private void ExecuteMe(string propertyName, object newValue) =>
            Console.WriteLine($"The property '{propertyName}' has a new value: '{newValue ?? ""}'");
    }

    [Logger]
    internal class Program
    {
        private static int Add(int a, int b) => a + b;

        private static void Main(string[] args)
        {
            Console.WriteLine(Add(5, 20));

            var sampleClass = new PropertySetterTestClass
            {
                BookName = "50 shades of C#",
                BookId = 23432
            };

            Console.ReadLine();
        }
    }
}

运行效果:

 

<think>嗯,用户要求用中文回答问题,并且最后必须提供3-5个相关问题。用户想要的是C#领域比较高深的课程或课题,看来是个有一定基础的开发者想进阶学习。 用户可能已经掌握了C#基础语法常见框架,现在想挑战更专业的领域。从"高深"这个词能感受到用户渴望突破技术瓶颈的诉求,或许ta在工作中遇到了复杂场景,或者单纯想提升技术深度。 我准备推荐几个真正有技术含量的方向:异步编程底层机制是个好选择,毕竟async/await背后涉及状态机、上下文等复杂概念;内存管理方面,GC机制unsafe代码优化对性能敏感场景很重要;LINQ的表达式树IQueryable原理也很硬核;还有AOP编程、动态代码生成这些能体现C#元编程能力的课题。 在推荐时要避免太理论化的内容,侧重能实际提升工程能力的课题。比如Roslyn编译器API虽然高深,但应用场景较窄;而并行编程或分布式事务就更贴近实战。 最后必须生成3-5个相关问题。这些问题要延续当前话题的深度:可以问具体技术细节(如Expression Tree原理)、应用场景(高并发下异步优化)、或者延伸方向(AOP框架比较)。每个问题都要确保能引发有价值的讨论。</think>以下是C#领域较高深的课程或课题方向,适合有扎实基础的开发者深入探索: --- ### **一、底层机制与高性能** 1. **内存管理与GC深度优化** - 深入CLR垃圾回收机制(分代/LOH/POH) - `Span<T>`/`Memory<T>`零拷贝技术实战 - 对象池(`ArrayPool`/`ObjectPool`)与栈上分配(`stackalloc`) ```csharp // 使用Span实现高效解析 ReadOnlySpan<char> data = "192.168.1.1"; var octets = new int[4]; for (int i = 0, pos = 0; i < 4; i++) { int dot = data.Slice(pos).IndexOf('.'); octets[i] = int.Parse(dot < 0 ? data.Slice(pos) : data.Slice(pos, dot)); pos += dot + 1; } ``` 2. **并发编程高阶** - `System.Threading.Channels`实现生产者-消费者模式 - 无锁数据结构(Interlocked/Volatile) - 异步状态机底层原理(ILSpy反编译async/await) --- ### **二、框架与架构设计** 1. **编译器级技术** - **Roslyn代码分析器开发**(自定义诊断/代码修复) - 表达式树(`Expression`)动态编译与IQueryable扩展 - Source Generator实现编译时代码生成 2. **分布式系统开发** - 基于`Dapr`的微服务架构(Actor模型/状态管理) - 分布式事务(Saga/2PC)在.NET中的实现 - 高并发场景下的限流熔断(Polly高级策略) --- ### **三、前沿技术融合** 1. **跨平台与云原生** - WASM运行时实战(Blazor WebAssembly AOT编译) - Kubernetes Operator开发(Kube.NET SDK) - 无服务器架构(Azure Functions高级触发器) 2. **AI集成开发** - ML.NET自定义模型训练(TensorFlow.NET集成) - 语义Kernel构建AI Agent链 --- ### **四、专项突破** 1. **AOP高阶应用** - 基于`DispatchProxy`或`Castle.DynamicProxy`实现动态拦截 - 编译时AOPFody插件开发) 2. **安全工程** - 代码混淆(Dotfuscator) - 内存加密技术(SecureString替代方案) ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值