PostSharp:OnMethodBoundaryAspect没有被调用

时间:2009-09-13 16:23:32

标签: c# aop castle-activerecord postsharp

我正在使用PostSharp将CompoundAspect应用于ActiveRecord类(来自CastleProject)。代码如下所示:

public override void ProvideAspects(object targetElement, LaosReflectionAspectCollection collection)
{
    Type targetType = (Type)targetElement;
    RevertibleSubAspect revertible = new RevertibleSubAspect();
    revertible.Cascade = this.Cascade;
    collection.AddAspect(targetType, revertible);

    //This isn't working
    MethodInfo saveMethod = targetType.GetMethod("Save");
    collection.AddAspect(saveMethod, new CommitOnSaveSubAspect());

    foreach (PropertyInfo property in targetType.GetProperties())
    {
        if((this.Only != null && this.Only.IndexOf(property.Name) == -1) ||
           (this.Except != null && this.Except.IndexOf(property.Name) > -1))
        {
            continue;
        }

        if (property.DeclaringType == targetType && property.CanWrite)
        {
            MethodInfo method = property.GetSetMethod();
            if (method != null && !method.IsStatic)
            {
                collection.AddAspect(method, new TrackInitialPropertyValuesSubAspect());
            }
        }
    }
}

除了CommitOnSaveSubAspect(OnMethodBoundaryAspect)之外,一切正常。调用Save方法时,永远不会调用OnSuccess方法。我已经尝试将代码移动到OnEntry和OnExit,但这里的情况相同。

CommitOnSaveSubAspect类如下所示:

[Serializable]
class CommitOnSaveSubAspect : OnMethodBoundaryAspect
{
    public override void OnSuccess(MethodExecutionEventArgs eventArgs)
    {
        ((IRevertible)eventArgs.Instance).Commit();
    }
}

我是否以错误的方式应用方面?

2 个答案:

答案 0 :(得分:2)

调试方面的一个好方法是使用Reflector查看生成的程序集。是否按预期增强了方法?

您还可以通过在其中放置断点并使用以下命令行运行msbuild来调试ProvideAspects方法:

msbuild /p:PostSharpAttachDebugger=true

答案 1 :(得分:0)

安装后是否全局定义了PostSharp?否则,您必须编辑项目文件,以便将PostSharp正确地注入到程序集中。

请参阅http://doc.postsharp.org/1.0/Default.aspx##PostSharp.HxS/UserGuide/Platform/EnablingPostSharp.html