Open sandboxFocusImprove this doc

LAMA0320: Aspects can't be applied to source-generated code

Severity Warning
Reported by Metalama.Framework
Message The aspect '<AspectType>' cannot be applied to '<Target>' because it is in source-generated code.<Addendum>

Cause

Source generators add code to your project during compilation. Metalama doesn't support aspects on declarations of this generated code. In particular, at design time, Metalama itself runs as a source generator, and it can't see the output of other source generators.

An analyzer included in the Metalama.Framework package reports LAMA0320 when it finds an aspect attribute on a declaration (a type, method, property, field, event, or parameter) whose syntax tree was produced by a source generator. The most common case is a custom attribute written in a Razor (.razor) or Razor Pages (.cshtml) file, because the Razor compiler turns these files into C# with a source generator. In this case, <Addendum> adds a suggestion to move the code to a code-behind file. In other cases, <Addendum> is empty. <AspectType> is the name of the aspect and <Target> is the target declaration.

This diagnostic requires a source generator and is reported by a Roslyn analyzer, which doesn't run in the snapshot tests of this documentation, so the article has no example.

Resolution

  • For Razor components and pages, move the member that needs the aspect from the @code block to a code-behind file, for instance a partial class in a MyComponent.razor.cs file, and add the aspect attribute there.
  • For other source generators, add the aspect to a declaration in your own source code. When the generated type is partial, declare the member in a partial part of the type in your source code, or add the aspect with a fabric to declarations in your source code.
  • If the generator is your own, generate code that doesn't contain aspect attributes.

See also