2016-05-30 2 views
0

Это мой код атрибута класса, который расширяет IMethodDecorator интерфейспараметров передают конструктору в методе Decorator Fody

[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.

+1

атрибутов в .NET позволяет параметр застройщик; вы пробовали 'public LogAttribute (string logMessage) {}'? – jlvaquero

+0

MethodDecorator 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")] 
Смежные вопросы