RJ Lohan
RJ Lohan

Reputation: 6527

PostSharp aspect to introduce an Interface AND LocationInterception pointcuts

I have a need to implement a complex aspect which needs to be able to introduce an interface, as well as several pointcuts. I'm not sure how to do this.

My goal is to intercept some field setters on a class, so that I can introduce some behaviour (via event handlers on the decorated fields). I want to transform some data, and then raise an event which is declared on a specific interface, so I want to introduce this interface to the class which contains these fields.

The simplest concept would be a container which captures all events on its children and transforms them into a single external event on the container class.

So, I know how to introduce method pointcuts using LocationInterceptionAspect;

public override void OnSetValue(LocationInterceptionArgs args)
{
    // attach event handler to args.Value.SomeEvent,
}

And also how to introduce interfaces/methods with an InstanceLevelAspect.

But not how to combine the 2 into a single aspect.

I can't simply introduce an interface or member inside a LocationInterceptionAspect, as the scope is the location, not the containing type, and it won't compile.

I could always separate this into 2 aspects, however this means each aspect will not function independently, and I'd have to ensure both are always applied together.

Upvotes: 1

Views: 416

Answers (1)

RJ Lohan
RJ Lohan

Reputation: 6527

It appears that I can add an OnLocationSetValueAdvice (via attributes) to an InstanceLevelAspect, and this works.

[IntroduceInterface(typeof(IMyInterface)]
public class CustomAspect : InstanceLevelAspect
{
    [OnLocationSetValueAdvice]
    [MulticastPointcut(Targets = MulticastTargets.Field, Attributes = MulticastAttributes.Instance)]
    public void OnSetValue(LocationInterceptionArgs args)
    {
       ...
    }
}

Upvotes: 1

Related Questions