pamidur / aspect-injector

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

Get method name that called a constructor #130

Closed vdurante closed 4 years ago

vdurante commented 4 years ago

I am attempting to implement an Aspect/Advice that targets a constructor capable of getting the name of the method that is instantiating an object of that class. Is it possible to do so?

[Aspect(Scope.Global)]
[Injection(typeof(ConstructorInterceptor ))]
public class ConstructorInterceptor : Attribute
{
    [Advice(Kind.Before, Targets = Target.Constructor)]
    public void Before(
        [Argument(Source.Metadata)] MethodBase name,
        [Argument(Source.Arguments)] object[] args,
        [Argument(Source.Type)] Type hostType,
        [Argument(Source.Instance)] object instance)
    {
        // I am attempting to get the method here
    }
}

public abstract class ConstructorBase
{
    public string CallerName { get; set; }

    [ConstructorInterceptor ]
    public ConstructorBase()
    {
    }
}

public class MyClass : ConstructorBase
{
}

// ...
// certain method
    public void Test(){
        var test = new MyClass();
    }
// ...
YuriyIvon commented 4 years ago

You can try using StackTrace class like in this example:

var st = new StackTrace();
// prints the name of the calling method (frame with index 0 represents the current method, 1 - its caller, etc.)
Console.WriteLine(st.GetFrame(1).GetMethod().Name);
vdurante commented 4 years ago

@YuriyIvon thank you. I was trying to avoid using StackTrace and thought maybe with AspectInjector there would be another way around. Thanks.