3
votes

New to PostSharp --- I'm trying out the NuGet version now and I'm trying to understand wny in the AuthoriseAttribute OnEntry method that the agrs.Instance value is null. I'm trying to implement authorsation that depends on the values of the object e.g. A customer who's been archived can't have a credit limit raised. I'm implementing the rules within other classes specific to the rules.

public class Program
{
    static void Main(string[] args)
    {
        var c = new Customer();
        c.RaiseCreditLimit(100000);
        c.Error(00); 
    }
}

public class Customer
{
    [AuthorizeActivity]
    public void RaiseCreditLimit(int newValue)
    {
    }

    [AuthorizeActivity]
    public void Error(int newValue)
    {

    }
}

[Serializable]
public class AuthorizeActivityAttribute : OnMethodBoundaryAspect
{
    public override void OnEntry(MethodExecutionArgs args)
    {
        //
        //Why is args.Instance null???????????
        //
        if (args.Method.Name == "RaiseCreditLimit")
        {
            Debug.WriteLine(args.Method.Name + " started");
        }
        else
        {
            throw new Exception("Crap");
        }
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        Debug.WriteLine(args.Method.Name + " finished");
    }
}
1
Did you get this figured out? - Dustin Davis

1 Answers

7
votes

The answer is because you're not using it in your aspect. It's an optimization. If you use it in the aspect then it will be set. Change your aspect to consume instance and it will be there.

public override void OnEntry(MethodExecutionArgs args)
        {
            //
            //Why is args.Instance null???????????
            //
            if (args.Method.Name == "RaiseCreditLimit")
            {
                Debug.WriteLine(args.Instance.GetType().Name);
                Debug.WriteLine(args.Method.Name + " started");
            }
            else
            {
                throw new Exception("Crap");
            }
        }

For more info check out this article to see what else PostSharp does to optimize code http://programmersunlimited.wordpress.com/2011/03/23/postsharp-weaving-community-vs-professional-reasons-to-get-a-professional-license/