Search code examples
c#aoppostsharp

Postsharp move some logic from run time to compile time based on condition


I have an attribute:

[Serializable()]
[IntroduceInterface(typeof(IPersistable), OverrideAction = InterfaceOverrideAction.Ignore)]
[MulticastAttributeUsage(MulticastTargets.Class)]
public sealed class PersistableAttribute : InstanceLevelAspect, IPersistable
{
    //TODO: revise: move some to compile time
    [OnLocationSetValueAdvice(), MulticastPointcut(Targets = MulticastTargets.Property, Attributes = MulticastAttributes.Instance | MulticastAttributes.NonAbstract)]
    public void OnPropertySet(LocationInterceptionArgs args)
    {
        // sets the value.
        args.ProceedSetValue();

        if(Validate(args.Location.PropertyInfo))
        {
            Work();//Some time-consuming work
        }
    }
}

At run-time, Work() and Validate() uses too much time. Because there are too many property changes and on each property change, Validate() is being called. I am looking for a way to move the injection of this OnPropertySet to compile time. i.e. at compile-time, when Validate(args.Location.PropertyInfo) == true, inject Work(), else do nothing (not even validate)

Thanks in advance.


Solution

  • You should do your build-time validation by overriding the method named CompileTimeValidate. If you need OnPropertySet to be applied to a subset of properties only, use a MethodPointcut; you also do your validation in the method implementing the pointcut (do a yield return method only if the method is valid).