pamidur / aspect-injector

AOP framework for .NET (c#, vb, etc)
Apache License 2.0
742 stars 111 forks source link

How to create a aspect with parameters ? #169

Closed fengqiaoyexia closed 2 years ago

fengqiaoyexia commented 2 years ago

Thank you for the library 。 I have a question about how to create a aspect with parameters. Code: ` [Aspect(Scope.PerInstance)] [AttributeUsage(AttributeTargets.All)] [Injection(typeof(LogCallAttribute))] public class LogCallAttribute : Attribute { private LogLevel _logLevel;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="logLevel"></param>
    public LogCallAttribute(LogLevel logLevel)
    {
        _logLevel = logLevel;
    }
 }

` Please look at this screenshot: 微信图片_20211225141621

I want to set up a Loglevel when using it 。But I find it impossible to set it like screenshot。

pamidur commented 2 years ago

Hi @fengqiaoyexia , for this you'll have to split attribute from aspect like this:

internal class Program
    {
        public static void Main(string[] args)
        {
            Do();
            Console.ReadLine();
        }

        [LogCall(LogLevel.Debug)]
        public static void Do() { }
    }

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    [Injection(typeof(LogAspect))]
    public class LogCall : Attribute
    {
        public LogLevel LogLevel { get; }
        public LogCall(LogLevel logLevel) => LogLevel = logLevel;

    }

    [Aspect(Scope.Global)]
    public class LogAspect
    {
        [Advice(Kind.Before)]
        public void LogEnter([Argument(Source.Name)] string name, [Argument(Source.Triggers)] Attribute[] triggers)
        {
            var trigger = triggers.OfType<LogCall>().First();

            Console.WriteLine($"Calling '{name}' method with loglevel {trigger.LogLevel}");
        }
    }
fengqiaoyexia commented 2 years ago

Oh! So it can be! I seem to know how to do it I wll try

Thank you for your answer ~ Merry Christmas!

pamidur commented 2 years ago

Thank you and Merry Christmas to you too @fengqiaoyexia !