Implementing interfaces
Some aspects need to modify the target type to implement a new interface. This can be done only by using the programmatic advising API.
Step 1. Call IAdviceFactory.ImplementInterface
In your implementation of the BuildAspect method, call the ImplementInterface method.
Step 2. Add interface members to the aspect class
Add all interface members to the aspect class and mark them with the [InterfaceMember] custom attribute. There is no need to have the aspect class implement the introduced interface.
The following rules apply to interface members:
- The name and the signature of all template interface members must match exactly those of the introduced interface.
- The accessibility of introduced members is irrelevant.
- The aspect framework will generate public members unless the IsExplicit property is set to true. In this case, an explicit implementation is created.
Implementing an interface in a completely dynamic manner, i.e., when the aspect does not already know the interface, is not yet supported.
Example: IDisposable
The aspect in the following example introduces the IDisposable
interface. The implementation of the Dispose
method disposes of all fields or properties that implement the IDisposable
interface.
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using System;
4using System.Linq;
5
6namespace Doc.Disposable
7{
8 internal class DisposableAttribute : TypeAspect
9 {
10 public override void BuildAspect( IAspectBuilder<INamedType> builder )
11 {
12 builder.Advice.ImplementInterface(
13 builder.Target,
14 typeof(IDisposable),
15 whenExists: OverrideStrategy.Ignore );
16 }
17
18 // Introduces a the `Dispose(bool)` protected method, which is NOT an interface member.
19 [Introduce( Name = "Dispose", IsVirtual = true, WhenExists = OverrideStrategy.Override )]
20 protected void DisposeImpl( bool disposing )
21 {
22 // Call the base method, if any.
23 meta.Proceed();
24
25 var disposableFields = meta.Target.Type.FieldsAndProperties
26 .Where( x => x.Type.Is( typeof(IDisposable) ) && x.IsAutoPropertyOrField == true );
27
28 // Disposes the current field or property.
29 foreach ( var field in disposableFields )
30 {
31 field.Value?.Dispose();
32 }
33 }
34
35 // Implementation of IDisposable.Dispose.
36 [InterfaceMember]
37 public void Dispose()
38 {
39 meta.This.Dispose( true );
40 }
41 }
42}
1using System.IO;
2using System.Threading;
3
4namespace Doc.Disposable
5{
6 [Disposable]
7 internal class Foo
8 {
9 private CancellationTokenSource _cancellationTokenSource = new();
10 }
11
12 [Disposable]
13 internal class Bar : Foo
14 {
15 private MemoryStream _stream = new();
16 }
17}
1using System;
2using System.IO;
3using System.Threading;
4
5namespace Doc.Disposable
6{
7 [Disposable]
8 internal class Foo : IDisposable
9 {
10 private CancellationTokenSource _cancellationTokenSource = new();
11
12 public void Dispose()
13 {
14 this.Dispose(true);
15 }
16
17 protected virtual void Dispose(bool disposing)
18 {
19 this._cancellationTokenSource.Dispose();
20 }
21 }
22
23 [Disposable]
24 internal class Bar : Foo
25 {
26 private MemoryStream _stream = new();
27
28 protected override void Dispose(bool disposing)
29 {
30 base.Dispose(disposing);
31 this._stream.Dispose();
32 }
33 }
34}
Example: Deep cloning
1using Metalama.Framework.Aspects;
2using Metalama.Framework.Code;
3using Metalama.Framework.Code.SyntaxBuilders;
4using System;
5using System.Linq;
6
7namespace Doc.DeepClone
8{
9 [Inheritable]
10 public class DeepCloneAttribute : TypeAspect
11 {
12 public override void BuildAspect( IAspectBuilder<INamedType> builder )
13 {
14 builder.Advice.IntroduceMethod(
15 builder.Target,
16 nameof(this.CloneImpl),
17 whenExists: OverrideStrategy.Override,
18 buildMethod: t =>
19 {
20 t.Name = "Clone";
21 t.ReturnType = builder.Target;
22 } );
23
24 builder.Advice.ImplementInterface(
25 builder.Target,
26 typeof(ICloneable),
27 whenExists: OverrideStrategy.Ignore );
28 }
29
30 [Template( IsVirtual = true )]
31 public virtual dynamic CloneImpl()
32 {
33 // This compile-time variable will receive the expression representing the base call.
34 // If we have a public Clone method, we will use it (this is the chaining pattern). Otherwise,
35 // we will call MemberwiseClone (this is the initialization of the pattern).
36 IExpression baseCall;
37
38 if ( meta.Target.Method.IsOverride )
39 {
40 baseCall = meta.Base.Clone();
41 }
42 else
43 {
44 baseCall = meta.Base.MemberwiseClone();
45 }
46
47 // Define a local variable of the same type as the target type.
48 var clone = meta.Cast( meta.Target.Type, baseCall )!;
49
50 // Select clonable fields.
51 var clonableFields =
52 meta.Target.Type.FieldsAndProperties.Where(
53 f => f.IsAutoPropertyOrField == true &&
54 ((f.Type.Is( typeof(ICloneable) ) && f.Type.SpecialType != SpecialType.String) ||
55 (f.Type is INamedType { BelongsToCurrentProject: true } fieldNamedType &&
56 fieldNamedType.Enhancements().HasAspect<DeepCloneAttribute>())) );
57
58 foreach ( var field in clonableFields )
59 {
60 // Check if we have a public method 'Clone()' for the type of the field.
61 var fieldType = (INamedType) field.Type;
62 var cloneMethod = fieldType.Methods.OfExactSignature( "Clone", Array.Empty<IType>() );
63
64 IExpression callClone;
65
66 if ( cloneMethod is { Accessibility: Accessibility.Public } ||
67 fieldType.Enhancements().HasAspect<DeepCloneAttribute>() )
68 {
69 // If yes, call the method without a cast.
70 callClone = field.Value?.Clone()!;
71 }
72 else
73 {
74 // If no, explicitly cast to the interface.
75 callClone = (IExpression) ((ICloneable?) field.Value)?.Clone()!;
76 }
77
78 if ( cloneMethod == null || !cloneMethod.ReturnType.ToNullableType().Is( fieldType ) )
79 {
80 // If necessary, cast the return value of Clone to the field type.
81 callClone = (IExpression) meta.Cast( fieldType, callClone.Value );
82 }
83
84 // Finally, set the field value.
85 field.With( (IExpression) clone ).Value = callClone.Value;
86 }
87
88 return clone;
89 }
90
91 [InterfaceMember( IsExplicit = true )]
92 private object Clone()
93 {
94 return meta.This.Clone();
95 }
96 }
97}
1using System;
2
3namespace Doc.DeepClone
4{
5 internal class ManuallyCloneable : ICloneable
6 {
7 public object Clone()
8 {
9 return new ManuallyCloneable();
10 }
11 }
12
13 [DeepClone]
14 internal class AutomaticallyCloneable
15 {
16 private int _a;
17 private ManuallyCloneable? _b;
18 private AutomaticallyCloneable? _c;
19 }
20
21 internal class DerivedCloneable : AutomaticallyCloneable
22 {
23 private string? _d;
24 }
25}
1using System;
2
3namespace Doc.DeepClone
4{
5 internal class ManuallyCloneable : ICloneable
6 {
7 public object Clone()
8 {
9 return new ManuallyCloneable();
10 }
11 }
12
13 [DeepClone]
14 internal class AutomaticallyCloneable : ICloneable
15 {
16 private int _a;
17 private ManuallyCloneable? _b;
18 private AutomaticallyCloneable? _c;
19
20 public virtual AutomaticallyCloneable Clone()
21 {
22 var clone = ((AutomaticallyCloneable)base.MemberwiseClone())!;
23 clone._b = (ManuallyCloneable?)this._b?.Clone()!;
24 clone._c = this._c?.Clone()!;
25 return clone;
26 }
27
28 object ICloneable.Clone()
29 {
30 return Clone();
31 }
32 }
33
34 internal class DerivedCloneable : AutomaticallyCloneable
35 {
36 private string? _d;
37
38 public override DerivedCloneable Clone()
39 {
40 var clone = ((DerivedCloneable)base.Clone())!;
41 return clone;
42 }
43 }
44}
Referencing interface members in other templates
When introducing an interface member to the type, you often want to access it from templates. Unless the member is an explicit implementation, you have two options:
Option 1. Access the aspect template member
this.Dispose();
Option 2. Use meta.This
and write dynamic code
meta.This.Dispose();
Accessing explicit implementations
The following strategies are possible to access explicit implementations:
Cast the instance to the interface and access the member:
((IDisposable)meta.This).Dispose();
Introduce a private method with the concrete method implementation, and call this private member both from the interface member and the templates.