Interface Implementation by Aggregation

by Gael Fraiteur on 26 Nov 2006

I have written that the newly redesigned Code Weaver now support type-level advices (well, to be precise, type-level join points). The first implementation is the new AggregationAspect

in PostSharp Laos.

So what's aggregation?

Say you want to implement a collection (ICollection) based on an ArrayList, but you want to hide ArrayList and don't want to implement each method manually. PostSharp can do it for you.

Look at the following code sample:

[SimpleAggregate(

ImplementationType=typeof(ArrayList),

InterfaceType=typeof(ICollection))]

internal class AggregatedCollection

{

}

After processing by PostSharp, the AggregatedCollection class will implement the ICollection collection using the ArrayList implementation.

Looks magic? If you inspect the generated code (the Roeder's Reflector is always useful for this), you will see a new field ~aggregated~0 of type ICollection and all methods of this interface, for instance:

IEnumerator IEnumerable.GetEnumerator()

{

return this.~aggregated~0.GetEnumerator();

}

The aggregated object is constructed inside the constructor of AggregatedCollection:

public AggregatedCollection()

{

this.~aggregated~0 = (ICollection)

~PostSharp~Laos~Implementation.customAttribute0.

CreateAggregatedObject(this);

}

Still looks magic?