Search code examples
c#postsharpaspect

PostSharp Class-Aspect to add aspects to all members of the class


Is there a way to mark a Class with an attribute, that will add attributes to all methods?

For Example:

[TestAspect]
public class Test
{
    public void foo() { ... };

    [AttributeA]
    public void bar() { ... };
}

Now the TestAspect should make it so, that Aspects are added to bar().

I've by writing an AspectProvider class, the following should apply AspectA and AspectB to all methods of the class, which have the AttributeA.

[Serializable, AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class TestAspect : TypeLevelAspect, IAspectProvider
{
    private static readonly CustomAttributeIntroductionAspect aspectA =
     new CustomAttributeIntroductionAspect(
        new ObjectConstruction(typeof(AspectB).GetConstructor(Type.EmptyTypes)));

    private static readonly CustomAttributeIntroductionAspect aspectB =
    new CustomAttributeIntroductionAspect(
        new ObjectConstruction(typeof(AspectA).GetConstructor(Type.EmptyTypes)));

    public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
    {
        Type targetClassType = (Type)targetElement;

        foreach(MethodInfo methodInfo in targetClassType.GetMethods())
        {
            if(!methodInfo.IsDefined(typeof(AttributeA), false))
            {
                yield break;
            }
            yield return new AspectInstance(targetElement, aspectA);
            yield return new AspectInstance(targetElement, aspectB);
    }
}

But the Attributes are not applied to the Methods unfortunately? No exception or error is thrown.

Does someone have an advice?


Solution

  • With the following Code I was able to at least add 1 Custom Attribute to the methods that are decorated with AttributeA in my Class, which is marked with TestClass.

    [Serializable, AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
    public class TestClassAttribute : TypeLevelAspect, IAspectProvider
    {
    
        public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
        {
            Type type = (Type)targetElement;
    
            return type.GetMethods().Where(method => method.GetCustomAttributes(typeof(AttributeA), false)
                    .Any()).Select(m => new AspectInstance(m, new CustomAttributeIntroductionAspect(
                        new ObjectConstruction(typeof(AttributeB).GetConstructor(Type.EmptyTypes)))));
        }
    }