Open sandboxFocusImprove this doc

LAMA0534: A field can't be introduced into an interface

Severity Error
Reported by Metalama.Framework
Message The aspect '<AspectType>' cannot introduce the field '<Member>' into interface type '<TargetType>'.

Cause

Interfaces describe a contract and don't hold instance state, so Metalama doesn't allow aspects to introduce fields into them. Metalama reports LAMA0534 when the target type of a field introduction is an interface, whether the field comes from a template marked with the [Introduce] attribute or from the IntroduceField method. The target can be an interface of your source code or an interface introduced by the aspect itself.

In the following example, the Versioned aspect introduces a _version field, but it's applied to an interface.

1using Metalama.Framework.Aspects;
2
3namespace Doc.LAMA0534.Error;
4
5public class VersionedAttribute : TypeAspect
6{
7    // Stores the version number of the entity.
8    [Introduce]
9    private int _version;
10}
11
1namespace Doc.LAMA0534.Error;
2
3// Error: the [Versioned] aspect introduces a field, but an interface can't contain instance fields.
4[Versioned]
Error LAMA0534: The aspect 'Versioned' cannot introduce the field 'IDocument._version' into interface type 'IDocument'.

5internal interface IDocument
6{
7    string Title { get; }
8}
9
10internal class Document : IDocument
11{
12    public string Title { get; set; } = "";
13}
14

Resolution

Do one of the following:

  • Apply the aspect to the classes or structs that implement the interface instead of the interface itself. The following example shows this fix.
  • If the interface must expose the value, introduce a property into the interface instead of a field.
  • If you're the author of the aspect, prevent it from being applied to interfaces by adding an eligibility condition in its BuildEligibility method.

1using Metalama.Framework.Aspects;
2
3namespace Doc.LAMA0534.Fixed;
4
5public class VersionedAttribute : TypeAspect
6{
7    // Stores the version number of the entity.
8    [Introduce]
9    private int _version;
10}
11
Source Code
1namespace Doc.LAMA0534.Fixed;
2

3internal interface IDocument
4{
5    string Title { get; }
6}
7
8// Fixed: the [Versioned] aspect is applied to the class that implements the interface.
9[Versioned]
10internal partial class Document : IDocument
11{
12    public string Title { get; set; } = "";
13}
14
Transformed Code
1namespace Doc.LAMA0534.Fixed;
2
3internal interface IDocument
4{
5    string Title { get; }
6}
7
8// Fixed: the [Versioned] aspect is applied to the class that implements the interface.
9[Versioned]
10internal partial class Document : IDocument
11{
12    public string Title { get; set; } = "";
13
14    private int _version;
15}
16

See also