如何在另一个项目中使用MethodDecorator.Fody Decorator

时间:2018-04-04 10:00:58

标签: c# nuget-package fody

我使用Fody Nuget包如下

  1. 安装包

    PM> Install-Package MethodDecorator.Fody
    
  2. 装饰方法

    public class BusinessLayerClass
    {
        [LogMethod] 
        public string BusinessLayerMethod()
        {
            DataLayerClass dataLayerClass = new DataLayerClass();
           return  dataLayerClass.DataLayerMethod();
        }
    }
    
  3. 编写拦截器

    using System;
    using System.Reflection;
    
    [module: LogMethod] // Attribute should be "registered" by adding as module or assembly custom attribute
    
    // Any attribute which provides OnEntry/OnExit/OnException with proper args
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module)]
    public class LogMethodAttribute : Attribute, IMethodDecorator
    {
        private MethodBase _method;
    
        // instance, method and args can be captured here and stored in attribute instance fields
        // for future usage in OnEntry/OnExit/OnException
    
        public void Init(object instance, MethodBase method, object[] args)
        {
            _method = method;
        }
    
        public void OnEntry()
        {
            NLogging.Trace("Entering into {0}", _method.Name);
        }
    
        public void OnExit()
        {
            NLogging.Trace("Exiting into {0}", _method.Name);
        }
    
        public void OnException(Exception exception)
        {
            NLogging.Trace(exception, "Exception {0}", _method.Name);
        }
    }
    
  4. 这在同一个项目中工作正常但是当我在另一个项目中的另一个方法中使用装饰器[LogMethod]时,这个OnEntry()OnExit()OnException(Exception exception)方法不会触发。< / p>

    例如:

    [LogMethod]
    public void Another_Method_In_Seperate_Project()
    

    我添加了对定义了[LogMethod]的项目的引用。

    有没有人可以给我一个在其他项目中使用相同实现的方法,而无需在每个项目中执行LogMethodAttribute.cs(定义了[LogMethod])。

1 个答案:

答案 0 :(得分:1)

您还需要在其他项目中安装MethodDecorator.Fody nuget包(以及依赖项)。您还需要在该项目中添加另一个FodyWeavers.xml

相关问题