Search code examples
asp.netasp.net-coreattributes

Add Description Attribute to AutoMapper


I wanted to add a simple DescriptionAttribute to the CreateMap configuration:

public class AppAutoMapper : Profile
    {
        public AppAutoMapper()
        {
            [Description("Mapping the JToken to the App ID")]
            CreateMap<JToken, RAFApplicationID>().ForAllMembers(opt =>
            {
                //MAPPING TOKEN TO APP ID MODEL
            });
        }
    }

but it's showing an error:

Error   CS7014  Attributes are not valid in this context.

As I undertand it, the DescriptionAttribute can be used anywhere:

/// <summary>
/// Specifies a description for a property or event.
/// </summary>
[AttributeUsage(AttributeTargets.All)]
public class DescriptionAttribute : Attribute
{
    /// <summary>
    /// Specifies the default value for the <see cref='System.ComponentModel.DescriptionAttribute'/>,
    /// which is an empty string (""). This <see langword='static'/> field is read-only.
    /// </summary>
    public static readonly DescriptionAttribute Default = new DescriptionAttribute();

    public DescriptionAttribute() : this(string.Empty)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref='System.ComponentModel.DescriptionAttribute'/> class.
    /// </summary>
    public DescriptionAttribute(string description)
    {
        DescriptionValue = description;
    }

    /// <summary>
    /// Gets the description stored in this attribute.
    /// </summary>
    public virtual string Description => DescriptionValue;

    /// <summary>
    /// Read/Write property that directly modifies the string stored in the description
    /// attribute. The default implementation of the <see cref="Description"/> property
    /// simply returns this value.
    /// </summary>
    protected string DescriptionValue { get; set; }

    public override bool Equals([NotNullWhen(true)] object? obj) =>
        obj is DescriptionAttribute other && other.Description == Description;

    public override int GetHashCode() => Description?.GetHashCode() ?? 0;

    public override bool IsDefaultAttribute() => Equals(Default);
}

so why isn't this one working?


Solution

  • AttributeTargets.All means it allows using the attribute on all of these:

    • Assembly
    • Module
    • Class
    • Struct
    • Enum
    • Constructor
    • Method
    • Property
    • Field
    • Event
    • Interface
    • Parameter
    • Delegate
    • Return value
    • Generic parameter

    None of these match your case where you are trying to apply it to a statement within a constructor.