seveves
seveves

Reputation: 1282

Can I access custom method attributes with an aspect-oriented approach?

For example: I have a custom attribute class similar to the following:

[System.AttributeUsage(System.AttributeTargets.Method)
]
public class Yeah: System.Attribute
{
    public double whatever = 0.0;
}

Now I decorate some method with it like that:

[Yeah(whatever = 2.0)]
void SampleMethod
{
    // implementation
}

Is it possible to access the Yeah-attribute through injecting the code via aspects? I would prefer the postsharp framework for AOP but I am also happy with any other solution because I think that there is such a feature in postsharp but only available in the professional edition (mentioned here: PostSharp Blog)

Upvotes: 0

Views: 960

Answers (1)

Tony THONG
Tony THONG

Reputation: 772

Take a look on NConcern .NET AOP Framework. This is a new open source project on which I actively work.

//define aspect to log method call
public class Logging : IAspect
{
    //define method name console log with additional whatever information if defined.
    public IEnumerable<IAdvice> Advise(MethodInfo method)
    {
        //get year attribute
        var year = method.GetCustomAttributes(typeof(YearAttribute)).Cast<YearAttribute>().FirstOrDefault();

        if (year == null)
        {
            yield return Advice.Basic.After(() => Console.WriteLine(methode.Name));
        }
        else //Year attribute is defined, we can add whatever information to log.
        {
            var whatever = year.whatever;
            yield return Advice.Basic.After(() => Console.WriteLine("{0}/whatever={1}", method.Name, whatever));
        }
    }
}

public class A
{
    [Year(whatever = 2.0)]
    public void SampleMethod()
    {
    }
}

//Attach logging to A class.
Aspect.Weave<Logging>(method => method.ReflectedType == typeof(A));

//Call sample method
new A().SampleMethod();

//console : SampleMethod/whatever=2.0

My logging aspect simply write method name when method called. it include whatever information when it is defined.

Upvotes: 2

Related Questions