Skip to content

STJ source generator fails when defining the serializer context in 2 partial classes #99669

@hugoqribeiro

Description

@hugoqribeiro

Description

If you define a serializer context (JsonSerializerContext) in 2 partial classes, the source generator fails with errors and a warning like this:

Warning	CS8785	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.MyClass1.g.cs' of the added source file must be unique within a generator.

We are doing this to support the following scenario:

  • The first partial class is produced by a code generator based on metadata.
  • We let developers add the second partial class to include classes in the serializer context that are not known to the code generator.

Reproduction Steps

Define a set of classes that need to be serialized:

public class MyClass1
{
    // (...)
}

public class MyClass2
{
    // (...)
}

Define a serializer context in a partial class:

[JsonSerializable(typeof(MyClass1))]
internal partial class SerializerContext : JsonSerializerContext
{
}

Define another partial class for the same serializer:

[JsonSerializable(typeof(MyClass2))]
internal partial class SerializerContext
{
}

This is easily reproducible in a .NET 8 console app.

Expected behavior

The source generator should be able to generate without errors.

Actual behavior

The following errors are produced when building:

warning CS8785: 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.MyClass1.g.cs' of the added source file must be unique within a generator.

error CS0534: 'SerializerContext' does not implement inherited abstract member 'JsonSerializerContext.GetTypeInfo(Type)'

error CS0534: 'SerializerContext' does not implement inherited abstract member 'JsonSerializerContext.GeneratedSerializerOptions.get'

Regression?

This worked correctly in .NET 7.

Known Workarounds

Can't seam to find one...

Configuration

.NET 8.0.102

Other information

No response

Metadata

Metadata

Labels

area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions