【问题标题】:Pass parameters to the constructor in Method Decorator Fody将参数传递给 Method Decorator Fody 中的构造函数
【发布时间】:2016-05-30 10:11:34
【问题描述】:

这是我的扩展 IMethodDecorator 接口的属性类的代码

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Field)]
public class LogAttribute : Attribute, IMethodDecorator
{
    ILogger log = Logger.Factory.GetLogger<Logger>();
    String methodName;


    public LogAttribute() {
    }

    public void Init(object instance, MethodBase method, object[] args)
    {
        methodName = method.Name;
    }

    public void OnEntry()
    {
        Console.WriteLine(methodName);
        log.Debug(methodName);
    }

    public void OnExit()
    {
        Console.WriteLine("Exiting Method");
    }

    public void OnException(Exception exception)
    {
        Console.WriteLine("Exception was thrown");
    }

}

我希望能够将其用作

[log("some logmessage")]
void method() 
{
// some code  
}

有什么想法吗?我正在使用 Method Decorator Fody 包。

【问题讨论】:

  • .NET 中的属性允许参数构造函数;你试过public LogAttribute(string logMessage) { }吗?
  • MethodDecorator Fody 不适用于参数化构造函数。
  • @VasudhaGupta 是的。您需要提供一个重载的构造函数 - 一个不接受模块属性的参数,另一个带有您希望在装饰方法时传递的参数。

标签: c# aop cil fody


【解决方案1】:

所以我找到了解决问题的方法。

基本上我修改了我的类 -

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Field)]
public class LogAttribute : Attribute, IMethodDecorator
{
    ILogger log = Logger.Factory.GetLogger<Logger>();
    String methodName;

    public String logMessage { get; set; }

    private Lazy<IEnumerable<PropertyInfo>> _properties;
    public MethodBase DecoratedMethod { get; private set; }

    public LogAttribute() {
        this._properties = new Lazy<IEnumerable<PropertyInfo>>(() =>
         this.GetType()
             .GetRuntimeProperties()
             .Where(p => p.CanRead && p.CanWrite));
    }


    public void Init(object instance, MethodBase method, object[] args)
    {
        this.UpdateFromInstance(method);
        methodName = method.Name;
    }

    public void OnEntry()
    {
        log.Debug("Inside" + methodName);
        log.Debug(logMessage);
    }

    public void OnExit()
    {
        Console.WriteLine("Exiting Method");
    }

    public void OnException(Exception exception)
    {
        Console.WriteLine("Exception was thrown");
    }

    private void UpdateFromInstance(MethodBase method)
    {
        this.DecoratedMethod = method;
        var declaredAttribute = method.GetCustomAttribute(this.GetType());

        foreach (var property in this._properties.Value)
            property.SetValue(this, property.GetValue(declaredAttribute));

    }

}

现在我可以使用自定义属性,例如

 [Log(logMessage = "This is Debug Message")]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2015-10-11
    相关资源
    最近更新 更多