pamidur / aspect-injector

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

How to pass parameter to Aspect? #65

Closed drony closed 5 years ago

drony commented 6 years ago
[Aspect(Aspect.Scope.Global)]
public class LoggingAspect
{
    public IAspectLogger Logger { get; private set; }

    public bool DebugPurpose { get; set; }

    public LoggingAspect()
    {

    }

    public LoggingAspect(IAspectLogger logger, bool debugPurpose = false)
    {
        Logger = logger;

        DebugPurpose = debugPurpose;
    }
MrVerifit commented 6 years ago

Check issue #61, that may help you

pamidur commented 6 years ago
using AspectInjector.Broker;
using System;
using System.Reflection;
using static AspectInjector.Broker.Aspect;
using static AspectInjector.Broker.Advice;
using static AspectInjector.Broker.Advice.Type;
using static AspectInjector.Broker.Advice.Target;
using static AspectInjector.Broker.Advice.Argument;

namespace CustomAttrsTest
{
    public class TraceAspectOptions:Attribute
    {
        public bool Debug { get; set; }
    }

    [Aspect(Scope.Global)]
    public class TraceAspect
    {
        [Advice(Before, Method)]
        public void LogMethodEntry(
            [Argument(Source.Method)] MethodBase method, 
            [Argument(Source.Name)] string name)
        {
            var options = method.GetCustomAttribute<TraceAspectOptions>();
            var isDebug = options?.Debug ?? false;

            Console.WriteLine($"Log {(isDebug?"Debug":"NoDebug")}: {name}");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.TestMethod1();
            p.TestMethod2();

            Console.ReadLine();
        }

        [Inject(typeof(TraceAspect))]
        [TraceAspectOptions(Debug = false)]
        public void TestMethod1()
        {
            Console.WriteLine($"Method {nameof(TestMethod1)}");
        }

        [Inject(typeof(TraceAspect))]
        [TraceAspectOptions(Debug = true)]
        public void TestMethod2()
        {
            Console.WriteLine($"Method {nameof(TestMethod2)}");
        }
    }
}
pamidur commented 5 years ago

done in 2.0.0-beta1