Skip to content

KubernetesJson use of SourceGenerationContext #1674

Closed

Description

@IvanJosipovic

Summary

The client currently uses reflection-based serialization in non-AOT library even though a SourceGenerationContext is already generated.
This adds unnecessary reflection-based overhead.
Additionally, SourceGenerationContext is private and prevents us chaining it with our own custom IJsonTypeInfoResolver.

Current Behavior

  1. Non-AOT library use reflection-based serialization.
  2. The generated SourceGenerationContext is not used by default, even though it's in the library.
  3. Callers cannot compose their own resolvers since the generated context is not exposed.

Expected Behavior

  1. Non-AOT builds should use the generated SourceGenerationContext by default and fall back to reflection-based if type is missing.
  2. SourceGenerationContext should be public so that we can KubernetesJson.AddJsonOptions and append our own IJsonTypeInfoResolver for our CRDs.

Rationale

Proposed Changes

  1. Initialize the client’s default JsonSerializerOptions with the generated context:
     public static class KubernetesJson
     {
         private static readonly JsonSerializerOptions JsonSerializerOptions = new JsonSerializerOptions
         {
             #if !K8S_AOT
             TypeInfoResolver = JsonTypeInfoResolver.Combine(SourceGenerationContext.Default, new DefaultJsonTypeInfoResolver()) // Uses Source Generated IJsonTypeInfoResolver when available and falls back to reflection
             #else
             TypeInfoResolver = SourceGenerationContext.Default // Uses Source Generated IJsonTypeInfoResolver
             #endif
         };
    }
  2. Make SourceGenerationContext public
    This allows us to use KubernetesJson.AddJsonOptions and chain our own custom Source Generated IJsonTypeInfoResolver
      KubernetesJson.AddJsonOptions(x =>
      {
          x.TypeInfoResolver = JsonTypeInfoResolver.Combine(SourceGenerationContext.Default, MyCRDSourceGenerationContext.Default, new DefaultJsonTypeInfoResolver());
      });
  3. Remove src/KubernetesClient.Aot/KubernetesJson.cs as it is now redundant.

Happy to make this PR.

Thanks!

Activity

  1. changed the title [-]KubernetsJson use of SourceGenerationContext[/-] [+]KubernetesJson use of SourceGenerationContext[/+] on Oct 17, 2025
  2. tg123 commented on Oct 21, 2025

    @tg123
    Member

    Expected Behavior
    looked good to me, i remember there was some issue in net7 or8, using SourceGenerationContext would cause some json issue
    feel free to send pr to enable it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions