1

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.

Alwin S
  • 186
  • 1
  • 10
  • Why not just discard the old `ContractResolver` and construct a new one? – dbc Apr 28 '18 at 16:21
  • 1
    ... Oh, I see the problem. You're using `CamelCasePropertyNamesContractResolver` which shares contract information across all instances of each subtype. Instead, inherit from `DefaultContractResolver` and set `NamingStrategy = new CamelCaseNamingStrategy()` as is shown in [Json.Net: Html Helper Method not regenerating](https://stackoverflow.com/a/30743234/3744182). Then you will be able to refresh your contract information by simply constructing a new contract resolver. (In fact this may be a duplicate. Agree?) – dbc Apr 28 '18 at 16:23
  • @dbc you are right, creating my own ContractResolver with the CamelCaseNamingStrategy and constructing a new resolver-instance when something has changed solved it! If you add this as an answere I will mark it as solution. Yes, you could consider this as a borderline duplicate of the question you mentioned. Thx heaps! – Alwin S Apr 30 '18 at 08:24

0 Answers0