I am using a custom Json.NET contract resolver in my project which adds some more properties to the contract model.
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
AddSomeMorePropertiesToContract(contract, objectType);
return contract;
}
During the lifetime of the application this custom property-list of my models can change, some of the properties might be removed and some might be added.
However Json.NET resolves the JsonObjectContracts
and its properties only once when the type is used for the first time and caches it, so the the new properties-list is never applied!
Is there a way to tell Json.NET that it should reset its cache and resolve the contracts again?
The only workaround I found to achieve this is to store all contracts after they have been created and manually manipulate their properties when I want to update them:
public class MyContractResolver : CamelCasePropertyNamesContractResolver
{
private static List<JsonObjectContract> OldContracts { get; } = new List<JsonObjectContract>();
protected override JsonContract CreateContract(Type type)
{
var contract = base.CreateContract(type);
OldContracts.Add((JsonObjectContract)contract);
return contract;
}
public void UpdateContracts()
{
foreach (var oldContract in OldContracts)
{
oldContract.Properties.Clear();
var newContract = (JsonObjectContract)base.CreateContract(oldContract.UnderlyingType);
oldContract.Properties.AddRange(newContract.Properties);
}
}
This works, but instead of manually updating the properties, I would much prefere to only somehow reset the cache and let Json.NET resolve the contracts again on its own.