I've written a class in C# that implements PostSharp's IAspectProvider
interface. What I don't understand is what I'm supposed to do with it now that I have it. I can't seem to find any documentation on PostSharp's site that tells me what to do with this class once it's written.
Does PostSharp just automatically find this class because it's derived from IAspectProvider
and use it? Or is there a link available to a page that I have thus far been unable to find?
FWIW, the class is provided below. (MethodTracingAspect
is our custom aspect we're using for training.)
namespace LoggingSample
{
using System;
using System.Collections.Generic;
using System.Linq;
using PostSharp.Aspects;
internal class ProviderAspect : IAspectProvider
{
public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
{
var type = (Type) targetElement;
return type.GetMethods()
.Where(m => type.IsAssignableFrom(typeof(IReportBuilder))
&& m.IsPublic
&& m.Name == "Execute")
.Select(m => new AspectInstance(targetElement,
new MethodTracingAspect()));
}
}
}
For PostSharp, a class implementing IAspectProvider
is just another aspect and you need to apply it to target elements in the same way as any other aspect. So, usually, your aspect provider class should also derive from one of the attribute classes. Then you can apply it as an attribute to target element and this element will be passed into ProvideAspects
method during build time.
In your specific example you can derive from the TypeLevelAspect
, because you expect your targetElement
to be a type.
An example of the aspect provider is available on this documentation page: http://doc.postsharp.net/example-dataattributes
Example of aspect usage:
// Aspect class
[Serializable]
public class ProviderAspect : TypeLevelAspect, IAspectProvider
{
public IEnumerable<AspectInstance> ProvideAspects(object targetElement)
{
// ...
}
}
// Apply to a single type
[ProviderAspect]
public class TargetClass : IReportBuilder
{
public void Execute()
{
// ...
}
}
// Apply to many types
[assembly: ProviderAspect (AttributeTargetTypes="OurCompany.OurApplication.Reports.*")]
You can find more information about applying aspect to your code on this documentation page: http://doc.postsharp.net/applying-aspects
P.S. We will also review our documentation page for aspect providers and add the information about usage.