postsharpmethod-interception

Postsharp MethodInterceptionAspect get method return value


I have an implementation of MethodInterceptionAspect(PostSharp) but when I in the override OnInvoke method, the args.Method is null, I need to know the method return value type,

anyone know about?

[PSerializable]
public class PSHandleRequestAttribute : MethodInterceptionAspect
{
    public PSHandleRequestAttribute(bool readOnly = true) : base()
    {
        ReadOnly = readOnly;
    }

    #region Properties

    protected bool ReadOnly { get; set; }

    #endregion Properties

    #region Public Methods

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        var instance = args.Instance as IBusinessTransaction;
        var method = args.Method;
        if (instance.IsNull())
        {
            throw new Exception("Use PSHandleRequestAttribute only for IBusinessTransaction");
        }

        instance.OpenTransaction();

        try
        {
            args.Proceed();
            //base.OnInvoke(args);
            instance.CommitTransaction();
            return;
        }
        catch (Exception ex)
        {
            var errorMessage = instance.RollbackTransaction(ex);

            return;
        }
    }

    #endregion Public Methods
}

Solution

  • PostSharp optimizes the resulting code, so when the value of args.Method is not used anywhere, the optimizer skips some operations and passes null as the value.

    Once you use the value in your code, the value should appear.

    I'd also recommend you to do the usage validation in CompileTimeValidate method and emit a build time error message. This way you would catch a possible error in build time. See http://doc.postsharp.net/aspect-validation.