Передать параметры конструктору в Method Decorator Fody

Это мой код класса атрибутов, который расширяет интерфейс 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.


person Vasudha Gupta    schedule 30.05.2016    source источник
comment
Атрибуты в .NET позволяют использовать конструктор параметров; ты пробовал public LogAttribute(string logMessage) { }?   -  person jlvaquero    schedule 30.05.2016
comment
MethodDecorator Fody не работает с параметризованным конструктором.   -  person Vasudha Gupta    schedule 01.06.2016
comment
@VasudhaGupta Да, это так. Вам нужно предоставить перегруженный конструктор — один не принимает параметров для атрибута модуля, а другой с параметрами, которые вы хотели бы передать при оформлении своего метода.   -  person a11smiles    schedule 18.07.2019


Ответы (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")]
person Vasudha Gupta    schedule 01.06.2016