Project "Caravela" 0.3 / / Caravela Documentation / Conceptual Documentation / Creating Aspects / Advising Code / Implementing Interfaces

Implementing Interfaces

Many aspects need to modify the target type so it implements a new interface. This can be done only 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 signature of all interface members must exactly match.
  • The accessibility of introduced members have no importance.
  • The aspect framework will generate public members unless the IsExplicit property is set to true. In this case, an explicit implementation is generated.

Implementing an interface in a complete dynamic manner, when the interface itself is not known by the aspect, is not yet supported.

Example: deep cloning

                using System;
using System.Linq;
using Caravela.Framework.Aspects;
using Caravela.Framework.Code;

namespace Caravela.Documentation.SampleCode.AspectFramework.DeepClone
{
    public class DeepCloneAttribute : TypeAspect
    {
        public override void BuildAspectClass(IAspectClassBuilder builder)
        {
            builder.IsInherited = true;
        }

        public override void BuildAspect(IAspectBuilder<INamedType> builder)
        {
            var typedMethod = builder.Advices.IntroduceMethod(
                builder.Target,
                nameof(CloneImpl),
                whenExists: OverrideStrategy.Override);

            typedMethod.Name = "Clone";
            typedMethod.ReturnType = builder.Target;

            builder.Advices.ImplementInterface(
                builder.Target,
                typeof(ICloneable),
                whenExists: OverrideStrategy.Ignore);
        }

        [Template(IsVirtual = true)]
        public virtual dynamic CloneImpl()
        {
            // This compile-time variable will receive the expression representing the base call.
            // If we have a public Clone method, we will use it (this is the chaining pattern). Otherwise,
            // we will call MemberwiseClone (this is the initialization of the pattern).
            IExpression baseCall;

            if (meta.Target.Method.IsOverride)
            {
                meta.DefineExpression(meta.Base.Clone(), out baseCall);
            }
            else
            {
                meta.DefineExpression(meta.Base.MemberwiseClone(), out baseCall);
            }

            // Define a local variable of the same type as the target type.
            var clone = meta.Cast(meta.Target.Type, baseCall)!;

            // Select clonable fields.
            var clonableFields =
                meta.Target.Type.FieldsAndProperties.Where(
                    f => f.IsAutoPropertyOrField &&
                    ((f.Type.Is(typeof(ICloneable)) && f.Type.SpecialType != SpecialType.String) ||
                    (f.Type is INamedType fieldNamedType && fieldNamedType.Aspects<DeepCloneAttribute>().Any())));

            foreach (var field in clonableFields)
            {
                // Check if we have a public method 'Clone()' for the type of the field.
                var fieldType = (INamedType)field.Type;
                var cloneMethod = fieldType.Methods.OfExactSignature("Clone", Array.Empty<IType>());

                if (cloneMethod is { Accessibility: Accessibility.Public } ||
                     fieldType.Aspects<DeepCloneAttribute>().Any())
                {
                    // If yes, call the method without a cast.
                    field.Invokers.Base.SetValue(
                        clone,
                        meta.Cast(fieldType, field.Invokers.Base.GetValue(meta.This).Clone()));

                }
                else
                {
                    // If no, use the interface.
                    field.Invokers.Base.SetValue(
                        clone,
                        meta.Cast(fieldType, ((ICloneable)field.Invokers.Base.GetValue(meta.This)).Clone()));
                }
            }

            return clone;
        }

        [InterfaceMember(IsExplicit = true)]
        object Clone() => meta.This.Clone();

    }
}

              
                using System;

namespace Caravela.Documentation.SampleCode.AspectFramework.DeepClone
{
    class ManuallyCloneable : ICloneable
    {
        public object Clone()
        {
            return new ManuallyCloneable();
        }
    }

    [DeepClone]
    class AutomaticallyCloneable
    {
        int _a;

        ManuallyCloneable? _b;

        AutomaticallyCloneable? _c;
    }

    class DerivedCloneable : AutomaticallyCloneable
    {
        string? _d;
    }

}

              
                using System;

namespace Caravela.Documentation.SampleCode.AspectFramework.DeepClone
{
    class ManuallyCloneable : ICloneable
    {
        public object Clone()
        {
            return new ManuallyCloneable();
        }
    }

    [DeepClone]
    class AutomaticallyCloneable : ICloneable
    {
        int _a;

        ManuallyCloneable? _b;

        AutomaticallyCloneable? _c;


        public virtual AutomaticallyCloneable Clone()
        {
            var clone = (AutomaticallyCloneable)MemberwiseClone();
            clone._b = (ManuallyCloneable?)_b.Clone();
            clone._c = _c.Clone();
            return clone;
        }

        private AutomaticallyCloneable Clone_Source()
        {
            return default(AutomaticallyCloneable);
        }

        object ICloneable.Clone()
        {
            return Clone();
        }
    }

    class DerivedCloneable : AutomaticallyCloneable
    {
        string? _d;


        public override DerivedCloneable Clone()
        {
            var clone = (DerivedCloneable)base.Clone();
            return clone;
        }
    }

}
              

Referencing interface members in other templates

When you introduce an interface member to a type, your will 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:

  • cast the instance to the interface and access the member, e.g.

    ((IDisposable)meta.This).Dispose();
    
  • introduce a private method with the real method implementation, and call this private member both from the interface member and from other templates.