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

可紊 提交于 2019-12-24 01:55:27

问题


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";
    }

}

回答1:


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.



来源:https://stackoverflow.com/questions/23049735/how-do-you-intercept-method-calls-on-a-base-class-using-postsharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!