Skip to content

STJ source generator fails when two JsonSerializerContext derived types have same name in project #72671

@ithline

Description

@ithline

Description

System.Text.Json source generator fails to generate output when two or more classes derived from JsonSerializerContext share the same name, even though their full name is different.

Reproduction Steps

Declare two partial classes with nested JsonSerializerContext derived types with same name.

public partial class ModelA
{
    [JsonSerializable(typeof(ModelA))]
    private partial class SerializerContext : JsonSerializerContext
    {
    }
}

public partial class ModelB
{
    [JsonSerializable(typeof(ModelB))]
    private partial class SerializerContext : JsonSerializerContext
    {
    }
}

Expected behavior

Generator creates code for both types.

Actual behavior

Generator fails with the following message in visual studio

Generator 'JsonSourceGenerator' failed to generate source. It will not contribute to the output and compilation errors may occur as a result. Exception was of type 'ArgumentException' with message 'The hintName 'SerializerContext.g.cs' of the added source file must be unique within a generator. Parameter name: hintName' Generator threw the following exception: 'System.ArgumentException: The hintName 'SerializerContext.g.cs' of the added source file must be unique within a generator. Parameter name: hintName at Microsoft.CodeAnalysis.AdditionalSourcesCollection.Add(String hintName, SourceText source) at System.Text.Json.SourceGeneration.JsonSourceGenerator.Emitter.AddSource(String fileName, String source, Boolean isRootContextDef) at System.Text.Json.SourceGeneration.JsonSourceGenerator.Emitter.Emit() at System.Text.Json.SourceGeneration.JsonSourceGenerator.Execute(Compilation compilation, ImmutableArray``1 contextClasses, SourceProductionContext sourceProductionContext) at System.Text.Json.SourceGeneration.JsonSourceGenerator.<Initialize>b__2_3(SourceProductionContext spc, ValueTuple``2 source) at Microsoft.CodeAnalysis.UserFunctionExtensions.<>c__DisplayClass3_0``2.<WrapUserAction>b__0(TInput1 input1, TInput2 input2, CancellationToken token)'.

Regression?

No response

Known Workarounds

Rename serializer context types that both have different names.

Configuration

No response

Other information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions