Search code examples
c#postsharp

Does postsharp provide a simple way to apply a group of aspects


I have searched and searched, but I can't find anything even though it seems like quite a simple thing.

Basically I have 4 or 5 aspects which are usually applied together to the same method, but also need to be kept separate as they are required individually in many places also.

Does postsharp provide any way to say 'Adding this aspect to a method is the equivalent of adding these 4 other aspects together'?

I know you can combine aspects into a single aspect, but I don't want duplicate code in the combined and non-combined aspects and I equally don't want the mess of a whole stack of aspects declared above methods.

If anyone can suggest anything that would be a big help. Thanks in advance.


Solution

  • Easiest option is to implement IAspectProvider interface on a placeholder aspect:

    [Serializable]
    public class CombinedAspect : MethodLevelAspect, IAspectProvider
    {
        public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
        {
            yield return new AspectInstance(targetElement, new FirstAspect());
            yield return new AspectInstance(targetElement, new SecondAspect());
        }
    }
    

    As you can see, this interface can be quite powerful tool. Additionally you may want to know whether there actually is an aspect present on the declaration. This can be done using IAspectRepositoryService service:

    [Serializable]
    public class CombinedAspect : MethodLevelAspect, IAspectProvider
    {
        private int count = 0;
    
        public IEnumerable<AspectInstance> ProvideAspects( object targetElement )
        {
            IAspectRepositoryService repositoryService = PostSharpEnvironment.CurrentProject.GetService<IAspectRepositoryService>();
    
            if ( !repositoryService.HasAspect( targetElement, typeof(FirstAspect) ) )
                yield return new AspectInstance( targetElement, new FirstAspect() );
    
            if ( !repositoryService.HasAspect( targetElement, typeof(SecondAspect) ) )
                yield return new AspectInstance( targetElement, new SecondAspect() );
        }
    }
    

    However, this service is available only from PostSharp 4.0 onward.