dotnet / dotnet/aspnetcore

OpenAPI: De-duplicate XML documentation IDs for internal types

Open
#67,192 1 comment 1 reaction 0 assignees View on GitHub
area-minimal feature-openapi
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

## Issue Description
When generating OpenAPI documentation, duplicate XML documentation IDs can be emitted for non-generic types, specifically for internal classes with the same namespace in different referenced assemblies. This causes a runtime `ArgumentException: An item with the same key has already been added` when the generated cache is used.

This issue was partially addressed for generic types in [#64404](https://github.com/dotnet/aspnetcore/pull/64404), but the following scenarios remain unresolved:

- Internal types from different assemblies with the same namespace.
- Cases where the same type is referenced both from the compilation and from XML documentation files.

## Current Behavior
The generated `XmlCommentCache` class may contain duplicate entries for the same documentation ID, e.g.:

```csharp
cache.Add(@"T:SomeNamespace.SomeInternalType", new XmlComment(...));
cache.Add(@"T:SomeNamespace.SomeInternalType", new XmlComment(...)); // Duplicate
```

This results in a runtime exception when the cache is initialized.

## Proposed Solutions
The following approaches were discussed in [#64404](https://github.com/dotnet/aspnetcore/pull/64404):

1. **Use `TryAdd` in the dictionary**
Replace `cache.Add(key, value)` with `cache.TryAdd(key, value)` in the generated code. This would silently ignore duplicates, with the first occurrence winning.

2. **Smarter filtering**
Adjust the filtering logic in `XmlCommentGenerator.Parser.cs` to exclude internal types from referenced assemblies unless they are accessible from the application assembly (The part which moved out of #64404).

3. **Centralized de-duplication**
Add a de-duplication step in `XmlCommentGenerator.cs` or `XmlCommentGenerator.Emitter.cs` to ensure each documentation ID is only added once, with a clear priority (e.g., compilation comments take precedence over referenced XML files).

## Reproduction
See #64378

## Related Issues/PRs
- #64378 Original issue, partially fixed for generics
- #64404 PR fixing generic types, but de-duplication for non-generics was put out of scope

---
**My preference:** Centralized de-duplication or smarter filtering, as it is handled at compile time, reduces runtime size, and minimizes overhead. I am open to create an PR with the fix.

Cc: @Youssef1313.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.