如何在同一对象上应用的几个方面之间共享某些元数据?

时间:2015-03-29 13:27:34

标签: c# metaprogramming aop postsharp

我有这三个方面,适用于某些类:

[Serializable]
[MulticastAttributeUsage(PersistMetaData = true)]
public class MetaDataAspect : LocationInterceptionAspect, IInstanceScopedAspect
{
    public MetaData ThisMetaData = new MetaData();

    public object CreateInstance(AdviceArgs adviceArgs) { return MemberwiseClone(); }
    public void RuntimeInitializeInstance() {}
}

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method)]
public class CallInterceptionAspect : MethodLevelAspect, IMethodInterceptionAspect
{
    public void OnInvoke(MethodInterceptionArgs args){
        GetMetaData().ThisMetaData.Id = args.Arguments[0];
    }
}

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Property)]
public class WmiClassPropertyAspect : LocationInterceptionAspect
{
    public override void OnGetValue(LocationInterceptionArgs args)
    {
        args.Value = GetMetaData().ThisMetaData.Id;
    }
}

如何实施GetMetaData()方法,以便为我提供ThisMetaData元数据?

1 个答案:

答案 0 :(得分:1)

快速回答 - 介绍一个界面并从方法级方面使用它。

基本上您需要执行以下操作:

public interface IThisMetaDataProvider
{
    Metadata ThisMetadata {get;}
}

[Serializable]
[MulticastAttributeUsage(PersistMetaData = true)]
[IntroduceInterface(typeof(IThisMetadataProvider))]
public class MetaDataAspect : LocationInterceptionAspect, IInstanceScopedAspect
{
    public Metadata ThisMetadata {get; private set;}

    public void RuntimeInitializeInstance() { ThisMetadata = new Metadata(); }

    ...
}

[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method)]
public class CallInterceptionAspect : MethodLevelAspect, IMethodInterceptionAspect
{
    public void OnInvoke(MethodInterceptionArgs args)
    {
        ((IThisMetadataProvider)args.Instance).ThisMetaData.Id = args.Arguments[0];
    }
}

您还可以使用IAspectProviderIAspectRepositoryService(从4.0开始)在方法上使用CallInterception时自动向类提供MetaDataAspect。