Applying aspect on constructor in c# using PostSharp

余生颓废 提交于 2019-11-30 16:04:32

I think your main problem is you are trying to apply aspects on 3th party libraries (mscorlib). You can take a look at Dustin's blog post on how to do this which might help you out. Do take into account officially this isn't supported by PostSharp.

In order to apply aspects to a constructor you can probably use a TypeLevelAspect and a MulticastPointcut with its Targets set to e.g. InstanceConstructor.

When you can't use a TypeLevelAspect (e.g. you want to apply the aspect to events) I previously used a OnMethodEntryAdvice and a MethodPointCut. This allows you to search for the constructors manually.

[OnMethodEntryAdvice, MethodPointcut( "SelectConstructors" )]
public void OnConstructorEntry( MethodExecutionArgs args )
{
    ...
}

IEnumerable<ConstructorInfo> SelectConstructors( EventInfo target )
{
    return target.DeclaringType.GetConstructors(
        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic );
}

A more extended discussion how I applied this to initialize events from the constructor can be found on my blog.

The latest complete source code of this class can be found on github. I've made several changes since the blog post, but the principle of targeting constructors remains the same.

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