Skip to content

ImplementingAdvices

Pascal Craponne edited this page Feb 12, 2015 · 8 revisions

#Implementing advices

##A very small theory on it

In our implementation:

  • The advices are attribute implementations
  • The pointcuts are attributes applied to method, property, type or assembly

##Let's get practical

###Method advices

Here is a first method advice:

public class ADummyMethodAdvice : Attribute, IMethodAdvice
{
    // your only duty is to implement the method below...
    public void Advise(MethodAdviceContext context)
    {
        // ... and optionnally call the original method (this is usually a good idea)
        context.Proceed();
    }
}

Some special method advices are propery advices:

public class ADummyPropertyAdvice : Attribute, IPropertyAdvice
{
    public void Advise(PropertyAdviceContext context)
    {
        if(context.IsGetter)
        {
            context.Proceed();
            // you can check the return value here, by using context.ReturnValue
        }
        else
        {
            // you can check the setter value here, by using context.Value
            context.Proceed()
        }
    }
}

Info advices

A method info advice

public class ADummyMethodInfoAdvice : Attribute, IMethodInfoAdvice
{
    public void Advise(MethodInfoAdviceContext context)
    {
        // do what you want here
    }
}

And a property info advice:

public class ADummyPropertyInfoAdvice : Attribute, IPropertyInfoAdvice
{
    public void Advise(PropertyInfoAdviceContext context)
    {
        // do what you want here
    }
}

Please note that a single class can implement multiple advice interfaces (info advice and method advice, for example).

You can now learn how to use those advices.