tags:

views:

138

answers:

2

I only want this invoked when a property is set. Why is this not working?

[DirtyTrackingAttribute(AttributeTargetElements =
   PostSharp.Extensibility.MulticastTargets.Property)]
class Program
{

    public static string Test { get; set; }

    static void Main(string[] args)
    {
        TestIt();
        Test = "foo";
        Console.ReadKey();
    }

    private static void TestIt()
    {
      Console.WriteLine("Real method called");
    }
}

[Serializable]
public class DirtyTrackingAttribute : OnMethodInvocationAspect
{
    public override void OnInvocation(MethodInvocationEventArgs eventArgs)
    {
        Console.WriteLine("Property invoked");
        eventArgs.Proceed();
    }
}
A: 

What exactly IS happening? Can you provide more information...an exception report if one exists, etc?

jrista
Apologies, I left out the last sentence. Basically, Console.WriteLine("Property invoked") is called multiple times. Even if I do not set the property, it is still called.
Ah. From what I can see, you applied the aspect to all properties, everywhere...I think PostSharp allows you to use basic string patterns (maybe full regex?) to specify which properties should match. You could also apply the aspect directly to the property if you only want that one property to be intercepted.
jrista
I only want it called on properties, but it is being called on regular methods as well.
I can't be sure about this off the top of my head...but do you need to apply the attribute to the assembly for multicast targets to work? [assembly: DirtyTracking(...)]
jrista
I've tried it. No matter what it still gets called on constructors and other methods as well. Very frustrating....
It seems OnFieldAccessAspect is more appropriate for what I am doing.
I was digging around the PostSharp documentation. It seems you need to apply the MulticastAttributeUsageAttribute to your DirtyTrackingAttribute, and specify what targets are valid: "Just like normal custom attributes should be decorated with the [AttributeUsage] custom attribute, multicast custom attributes must be decorated by the [MulticastAttributeUsage] attribute". I can't link directly due to how the PostSharp.org site is organized, but its in the PostSharp LAOS documentation.
jrista
+1  A: 

If you want the aspect to be applied on property setters only, you can filter the method name with the expression "set_*":

[DirtyTrackingAttribute(AttributeTargetMembers="set_*")]

PostSharp 1.* does not support explicitely properties; property accessors are considered as plain methods.

Gael Fraiteur
Nice, I didn't know you could filter on property names directly on the attribute ...I've also just played once with PostSharp, where I wanted to intercept on property access as well, and this is how i've done it:http://fgheysels.blogspot.com/2008/08/locking-system-with-aspect-oriented.html
Frederik Gheysels