Can you use the same description in the ApiMember attribute and xmldoc summary comment?

Viewed 87

In my API's model assembly, I heavily use the ApiMember attribute to provide descriptions for the properties for Swagger UI, e.g.

public class FindVendorItems : IReturn<List<VendorItem>>, IGet
{
    [ApiMember(Descripton = Description.ItemId)]
    public int ItemId { get; set; }
}

The descriptions are constant strings in a static Description class so that they can be used throughout the model to keep the description consistent.

This works great for Swagger, but the problem I'd like to solve is getting those same descriptions into the summary tag of the XML documentation comments so they are usable and visible in Visual Studio. I don't want to copy/paste the description from the constant into the summary tag, as it's proven to be prone to errors and the two can quickly get out of sync.

public class FindVendorItems : IReturn<List<VendorItem>>, IGet
{
    /// <summary>
    /// Same Description.ItemId here
    /// </summary>
    [ApiMember(Descripton = Description.ItemId)]
    public int ItemId { get; set; }
}

Is there any way to do this automatically? Even if it's not visible like this in Visual Studio, it's fine as long as the resulting XML file generated by the build contains all the descriptions so IntelliSense is provided when the NuGet package built from this is consumed.

2 Answers

That's not possible because executing .NET Code does not have access to the external .xml files containing the XML API documentation that the development tools & IDEs have access to.

ServiceStack supports dynamically adding attributes so there's a potential for using some external code-gen tool to parse the XML documentation files and generate C# code to dynamically add the documentation attributes to your DTO Types on Startup.

I came up with a solution to this. I used XML documentation comments for all of the types and members in my model (request and response DTOs) and then wrote a custom ApiDeclarationFilter that parses the XML documentation files and replaces the description and summary properties in the Open API response with those from the XML docs.

In order to re-use the descriptions across types and members, I put the XML docs in a separate XML file and referenced the corresponding member using:

/// <include file='../XmlDocs.xml' path='members/member[@name="MyPropertyName"]/*' />
Related