Search code examples
c#.netpostsharpaop

reference to class property in OnMethodBoundaryAspect


Is it possible to reference in an aspect to properties of the class using the aspect?

following example:

public class Device
{
    public bool IsRunning { get; set; }
    public bool IsOffline { get; set; }

    [Offline]
    public void Start()
    {
        IsRunning = true;
    }

    [Offline]
    public void Stop()
    {
        IsRunning = false;
    }
}

[Serializable]
public class Offline : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        // should be something like
        if (device.IsOffline)
        {
            args.FlowBehavior = FlowBehavior.Return;
        }
    }
}

I want to intercept in OnEntry if the IsOffline property of the class is true. Of course there are many devices, therefore injection of one device to the aspect doesn't seem feasible.

Also, as it is an api I do not want do pass it as an argument (someDevice.Start(someDevice.IsOffline)), where I could get the state via it's MethodExecutionArgs.


Solution

  • 'args.Instance' will give you the instance where the aspect has been applied too.

    You will need to cast this to something that you'll be able to use, an Inteface being applied to all classes should be sufficient.