You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在其他项目中使用MethodDecorator.Fody装饰器?

如何在多个项目中复用MethodDecorator.Fody自定义装饰器

嘿,我之前也遇到过类似的复用MethodDecorator.Fody装饰器的需求,给你整理了一套清晰的步骤,保证能在其他项目里顺利用上你的[LogMethod]装饰器:


步骤1:把装饰器封装成可复用的类库

首先要把你的LogMethod特性和拦截逻辑从现有项目中抽离出来,做成一个独立的类库,这样其他项目可以直接引用:

  1. 在解决方案中新建一个类库项目(比如命名为CustomMethodDecorators)
  2. 在这个类库中安装MethodDecorator.Fody包:
    PM> Install-Package MethodDecorator.Fody
    
  3. 实现完整的LogMethod特性(注意必须实现IMethodDecorator接口,Fody靠这个识别拦截逻辑):
    using System;
    using System.Reflection;
    using MethodDecorator.Fody.Interfaces;
    
    public class LogMethodAttribute : Attribute, IMethodDecorator
    {
        private MethodBase _targetMethod;
        private object _instance;
    
        // 初始化:在装饰方法时被调用,可存储方法实例、方法信息
        public void Init(object instance, MethodBase method, object[] args)
        {
            _instance = instance;
            _targetMethod = method;
        }
    
        // 方法执行前触发
        public void OnEntry()
        {
            Console.WriteLine($"[LOG] 进入方法:{_targetMethod.DeclaringType.Name}.{_targetMethod.Name}");
        }
    
        // 方法执行完成后触发(无论是否抛出异常)
        public void OnExit()
        {
            Console.WriteLine($"[LOG] 退出方法:{_targetMethod.DeclaringType.Name}.{_targetMethod.Name}");
        }
    
        // 方法抛出异常时触发
        public void OnException(Exception exception)
        {
            Console.WriteLine($"[LOG] 方法异常:{_targetMethod.DeclaringType.Name}.{_targetMethod.Name},错误:{exception.Message}");
        }
    }
    
  4. 在类库的AssemblyInfo.cs中添加模块级注册(或者也可以在后续使用的项目中注册,推荐在类库中统一注册):
    [module: LogMethod]
    

步骤2:在目标项目中引用并配置

现在可以在其他项目中使用这个装饰器了:

  1. 右键目标项目 → 添加引用 → 选择刚才创建的CustomMethodDecorators类库
  2. 必须在目标项目中也安装MethodDecorator.Fody包(因为Fody是编译时织入工具,每个需要拦截的项目都得有编译阶段的支持):
    PM> Install-Package MethodDecorator.Fody
    
  3. (如果没在类库中注册)在目标项目的AssemblyInfo.cs或任意类文件顶部添加模块级注册:
    [module: LogMethod]
    

步骤3:实际使用示例

现在就可以在目标项目的任意方法上直接使用[LogMethod]装饰了:

public class OtherProjectBusinessClass
{
    [LogMethod]
    public string ProcessData(string input)
    {
        // 你的业务逻辑
        return $"Processed: {input}";
    }
}

关键注意事项

  • ✅ 每个使用装饰器的项目必须安装MethodDecorator.Fody,因为Fody是在编译时修改IL代码的,没有这个包就无法完成织入
  • ✅ 装饰器特性必须实现IMethodDecorator接口,否则Fody无法识别拦截逻辑
  • ✅ 模块级注册[module: LogMethod]是必填项,告诉Fody要处理这个特性的织入逻辑

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:41:32