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

How to share certain metadata between several aspects applied on the same object?

我有这三个方面,应用于某某class:

[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 元数据?

快答-介绍一个接口,从方法层面使用。

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

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 时自动向 class 提供 MetaDataAspect。