問題描述
將方面應用於其他程序集類方法調用 (apply an aspect to other assembly class methods calls)
我創建了一個簡單的方面:
[Serializable()]
public class NullableCallAspect : PostSharp.Aspects.OnMethodBoundaryAspect
{
public override void OnEntry(PostSharp.Aspects.MethodExecutionArgs args)
{
if (args.Instance == null)
args.FlowBehavior = PostSharp.Aspects.FlowBehavior.Return;
}
}
基本上,我希望 instance.method
調用 instance == null
'不要進入方法。我在想,我需要改變方面的繼承。因此,我需要將 OnMethodBoundaryAspect
更改為另一個。這將是第一個問題。
另一個問題是關於如何將這一方面應用於從繼承另一個程序集的接口的類中調用的方法。
我試過這個,但它並不完全有效:
[assembly: UI.Aspects.NullableCallAspect(
AttributeTargetAssemblies = "UIAppearanceExtensibility",
AttributeTargetTypes = "UI.Appearance.Extensibility.*.I*AppearanceManager",
AttributeTargetMembers = "handle*"
)]
參考解法
方法 1:
This kind of aspects would require call site interception which is not supported by PostSharp. Both OnMethodBoundaryAspect and MethodInterceptionAspect modify target method not call site itself ‑ instance is still required when calling method decorated by these aspects.
EDIT: There is a hack how to force PostSharp to intercept call sites. It is when an aspect is multicasted to types in different assembly. If all methods are implemented in project ClassLibrary1 and they are called just from MyApplication project then the aspect can be multicasted in MyApplication project like this:
[assembly:
NullableCallAspect(AttributeTargetAssemblies = "ClassLibrary1", AttributeTargetTypes = "ClassLibrary1.*",
AttributeTargetMembers = "handle*", AttributeTargetElements = MulticastTargets.Method)]
If there is a convention that all implementation of IAppearanceManager end has name with suffix AppearanceManager then the multicast needs to be changed:
[assembly:
NullableCallAspect(AttributeTargetAssemblies = "ClassLibrary1", AttributeTargetTypes = "ClassLibrary1.*AppearanceManager",
AttributeTargetMembers = "handle*", AttributeTargetElements = MulticastTargets.Method)]
If there is no such convention then a IAspectProvider can be used for the multicasting.
This is not usable when there are calls to methods decorated by NullableCallAspect within same assembly ‑ call sites are not intercepted in such case.
(by Jordi、Jakub Linhart)