diff --git a/src/Dahomey.Json.Tests/DiscriminatorTests.cs b/src/Dahomey.Json.Tests/DiscriminatorTests.cs index 46ce964..0ad0384 100644 --- a/src/Dahomey.Json.Tests/DiscriminatorTests.cs +++ b/src/Dahomey.Json.Tests/DiscriminatorTests.cs @@ -262,5 +262,26 @@ public void ReadPolymorphicObjectWithDeferredTypeProperty() Assert.Equal("foo", nameObject.Name); Assert.Equal(1, nameObject.Id); } + + [Fact] + public void ReadPolymorphicObjectWithBaseRegister() + { + const string json = @"{""BaseObject"":{""$type"":12,""Name"":""foo"",""Id"":1}}"; + + JsonSerializerOptions options = new JsonSerializerOptions(); + options.SetupExtensions(); + DiscriminatorConventionRegistry registry = options.GetDiscriminatorConventionRegistry(); + registry.ClearConventions(); + registry.RegisterConvention(new DefaultDiscriminatorConvention(options)); + registry.RegisterType(); + registry.RegisterType(); + + BaseObjectHolder obj = JsonSerializer.Deserialize(json, options); + + Assert.NotNull(obj); + Assert.IsType(obj.BaseObject); + Assert.Equal("foo", ((NameObject)obj.BaseObject).Name); + Assert.Equal(1, obj.BaseObject.Id); + } } } diff --git a/src/Dahomey.Json/Serialization/Conventions/DiscriminatorConventionRegistry.cs b/src/Dahomey.Json/Serialization/Conventions/DiscriminatorConventionRegistry.cs index 99f5b0e..2dbbb09 100644 --- a/src/Dahomey.Json/Serialization/Conventions/DiscriminatorConventionRegistry.cs +++ b/src/Dahomey.Json/Serialization/Conventions/DiscriminatorConventionRegistry.cs @@ -51,7 +51,17 @@ public void ClearConventions() public IDiscriminatorConvention? GetConvention(Type type) { - return _conventionsByType.GetOrAdd(type, t => InternalGetConvention(t)); + if(_conventionsByType.TryGetValue(type, out IDiscriminatorConvention? convention)) + { + return convention; + } + + convention = InternalGetConvention(type); + if(convention != null) + { + _conventionsByType.TryAdd(type, convention); + } + return convention; } public void RegisterAssembly(Assembly assembly)