Search code examples
c#aoppostsharp

How do you intercept method calls on a base class using PostSharp?


I want to provide an implementation of System.Object.ToString to various classes using PostSharp. I've created an aspect inheriting from MethodInterceptionAspect but the OnInvoke method isn't getting invoked when a call to EchoDto.ToString takes place.

How can I get OnInvoke to be called when ToString is called?

[DataContract]
[ImplementJsonToStringAspect()]
public class EchoDto
{

    [DataMember]
    public string Text { get; set; }

}

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method)]
public class ImplementJsonToStringAspect : MethodInterceptionAspect
{

    public override void OnInvoke(MethodInterceptionArgs args)
    {
        base.OnInvoke(args); // Never gets called
    }

    public override bool CompileTimeValidate(MethodBase method)
    {
        return method.Name == "ToString";
    }

}

Solution

  • Inherit from InstanceLevelAspect and decorate the method with [IntroduceMember(OverrideAction=MemberOverrideAction.OverrideOrFail)]. To reference this on the target object, use this.Instance.

    /// <summary>
    /// Implements a ToString method on the target class that serializes the members to JSON.
    /// </summary>
    [Serializable]
    public class ImplementJsonToStringAspect : InstanceLevelAspect
    {
    
        #region Methods
    
        /// <summary>
        /// Provides an implementation of <see cref="System.Object.ToString"/> that serializes the instance's
        /// public members to JSON.
        /// </summary>
        /// <returns></returns>
        [IntroduceMember(OverrideAction=MemberOverrideAction.OverrideOrFail)]
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this.Instance);
        }
    
        #endregion
    
    }
    

    Note: This requires the paid version of PostSharp as InstanceLevelAspect is not supported by the free version.